原文

 

Question:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

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

 

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

 

 


翻譯

 

問題:

給定一個整數陣列 nums 與一個特定值 T ,回傳一組index [ a , b] ,而使得 T = nums [a] + nums [b].

注意:不可重複使用同一個元素 Ex :  6 = 3 + 3 是不合法的。

 

解答:

int twoSum(int *nums ,int length, int target) 
{
    static int answer[2] = {0};
    
     for (int i = 0 ; i < length; i++)
     {
        for (int j = i+1 ; j < length ; j++)
        {
            if((nums [i] + nums [j]) == target)
            {
                answer[0] = i;
                answer[1] = j;
                    
                return answer;
            }
        }
     }
     return 0;
}

 

解析:

      此題為簡單的熱身題,使用一般暴力破解法,窮舉所有可能即可得到答案。

需要注意的是: 

1.  "所有可能" 只需檢查一次即可,所以 j = i+1 而非從 0 開始。

2.  宣告 int answer 時,記得加上 static 其目的是使陣列 answertwoSum() 結束時,依然可保留其記憶體位置而不被刪除。

arrow
arrow

    C 發表在 痞客邦 留言(0) 人氣()