[LeetCode] Two Sum

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/GYH0730/article/details/84032094

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;
    }
}

猜你喜欢

转载自blog.csdn.net/GYH0730/article/details/84032094