码迷,mamicode.com
首页 > 其他好文 > 详细

1. Two Sum

时间:2018-01-25 14:10:12      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:out   开始   []   hat   put   one   value   number   example   

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

1. Two Sum

标签:out   开始   []   hat   put   one   value   number   example   

原文地址:https://www.cnblogs.com/ctrlzhang/p/8350787.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!