👋

【C言語】Leet Code Probrems「1. Two Sum」解答例

2023/01/07に公開

はじめに
本記事ではLeetCodeのProblemの解答例を示す

問題
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

https://leetcode.com/problems/two-sum/

解答例

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int returnnums[100]; //演算結果を返却するための配列を宣言

int* twoSum(int* nums, int numsSize, int target, int* returnSize){
        int sum;
        returnSize[0] = 2; //演算結果を返却する配列の要素数を代入
        for(int i=0;i<numsSize;i++){ 
            for(int j=i+1;j<numsSize;j++){
                sum=nums[i]+nums[j]; //配列の組み合わせの和を演算してtargetと同じか計算
                if(sum==target){ //同じであれば返却用の配列に要素数を格納
                    returnnums[0]=i; 
                    returnnums[1]=j;                    
                    return returnnums;
                }
            }
    }
    return returnnums;
}

時間が掛かった箇所
・配列numsの全組み合わせの和を計算する2重ループの処理のところで、よくあるやり方なのに導くまでに時間がかかった。
・> returnSize[0] = 2
上記処理がなかったため、アウトプットが正解にならなかった。
ここは他の正答例を参考にして正解になったが、問題文を見てもこの処理が必要となるかが分かっていない…

まとめ
・今回の2重ループのような頻出される処理は使いこなせるようにする

Discussion