leetcode个人题解——two sum

这是leetcode第一题,通过较为简单。

第一题用来测试的,用的c,直接暴力法过,

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

官方还提供了hash表法,用的java

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        map.put(nums[i], i);
    }
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement) && map.get(complement) != i) {
            return new int[] { i, map.get(complement) };
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

猜你喜欢

转载自www.cnblogs.com/txltxl22/p/10334922.html