LeetCode 1 - Two Sum

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

 

vector<int> twoSum(vector<int>& nums, int target) {
    unordered_map<int,int> map;
    vector<int> res(2,-1);
    for(int i=0; i<nums.size(); i++) {
        int diff = target - nums[i];
        if(map.count(diff)) {
            res[0] = map[diff]+1;
            res[1] = i+1;
            break;
        } else {
            map[nums[i]] = i; 
        }
    }
    return res;
}

 

Java代码如下:

public int[] twoSum(int[] nums, int target) {
    int[] res = new int[2];
    Map<Integer, Integer> map = new HashMap<>();
    for(int i=0; i<nums.length; i++) {
        int key = target - nums[i];
        Integer val = map.get(key);
        if(val != null) {
            res[0] = val+1;
            res[1] = i+1;
            break;
        } else {
            map.put(nums[i], i);
        }
    }
    return res;
}
// if you just return the values, not the indices, you can also do this
public int[] twoSum0(int[] nums, int target) {
    Arrays.sort(nums);
    int[] res = new int[2];
    int start = 0, end = nums.length-1;
    while(start < end) {
        int sum = nums[start] + nums[end];
        if(sum < target) {
            end--;
        } else if(sum > target) {
            start++;
        } else {
            res[0] = nums[start];
            res[1] = nums[end];
            return res;
        }
    }
    return res;
}

 

你可能感兴趣的:(LeetCode)