1. 程式人生 > >[LeetCode] Two Sum

[LeetCode] Two Sum

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].

題意:給出一個數組,在這個陣列內找出兩個數(每個數只能用一次),這兩個數的和為target,把這兩個數的下標存到數組裡返回。

思路:雙層for列舉即可。

C程式碼:

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* twoSum(int* nums, int numsSize, int target) {
    int* array;
    for(int i = 0; i < numsSize; i++) {
        for(int j = 0; j < numsSize; j++) {
            if(i == j) continue;
            if(nums[i] + nums[j] == target) {
                array = (int*) malloc(sizeof(int) * 2);
                array[0] = i;
                array[1] = j;
                goto here; 
            }
        }
    }
    here:
    return array;
}

Java程式碼:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] array = new int[2]; 
        int i,j;
        boolean flag = false;
        for(i = 0; i < nums.length; i++) {
            for(j = 0; j < nums.length; j++) {
                if(i == j) continue;
                if(nums[i] + nums[j] == target) {
                    array[0] = i;
                    array[1] = j;
                    flag = true;
                    break;
                }
            }
            if(flag) {
                break;
            }
        }
        return array;
    }
}