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

解题思路:
使用hashmap, key为元素值, value为元素在数组中的下标. 从头开始遍历,假设遍历的元素为解的右半部分,则我们只需要考虑左半部分的值是否已经出现过,若已出现过,则根据hashmap,返回该下标和当前下标.

解法一:
时间复杂度o(n) 空间复杂度o(n)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] ans = new int[2];
        Map<Integer, Integer> mp = new HashMap<Integer, Integer>();
        for(int i = 0; i < nums.length; i++) {
            int d = nums[i];
            if(mp.containsKey(target - d)) {
                ans[1] = i;
                ans[0] = mp.get(target - d);
                return ans;
            } else {
                mp.put(d, i);
            }
        }
        return ans;
    }
}

解法二:
时间复杂度o(n) 空间复杂度o(n)

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int, int> mp;
        for(int d : nums) {
            mp[d]++;
        }
        
        vector<int> ans(2, -1);
        int l = INT_MIN, r = INT_MIN;
        for(int d : nums) {
            cout<<"d="<<d<<" "<<mp[target - d]<<endl;
            mp[d]--;
            if(mp.find(target - d) != mp.end() && mp[target - d] > 0) {
                l = d;
                r = target - d;
                break;
            }
            mp[d]++;
        }
        
        if(l == INT_MIN && r == INT_MIN) return ans;
        cout<<l<<" "<<r<<endl;
        int cnt = 0;
        for(int i = 0; i < nums.size() && cnt < 2; i++) {
            if(nums[i] == l) {
                ans[cnt] = i;
                cnt++;
            }  else if(nums[i] == r) {
                ans[cnt] = i;
                cnt++;
            }
        }
        return ans;
    }
};
posted @ 2018-01-25 13:18  JinleiZhang  阅读(113)  评论(0编辑  收藏  举报