美文网首页
1. Two Sum两数之和

1. Two Sum两数之和

作者: 这就是一个随意的名字 | 来源:发表于2017-07-31 09:20 被阅读0次

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.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
给定一个整数数组和一个目标数target,返回和恰好等于target的两个元素的序号,这里假定每个输入都有恰好唯一解。


思路
这类问题基本的思路是要顺序扫描数组,对于当前元素nums[i],扫描数组中是否存在元素target-nums[i],主要通过两种方式查找:

  1. 排序数组,二分查找,但此题目需要返回解元素的序号,因而此种方式不适用
  2. 构建一个哈希map,用于保存数组元素以及它们的序号,此方法遍历时间O(n),寻找时间O(1),总时间复杂度O(n),空间复杂度O(n)。
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int,int>  hash;
        vector<int> result;
        for(int i=0;i!=nums.size();i++){
            int numsToFind = target-nums[i];
            if(hash.find(numsToFind)!=hash.end()){
                result.push_back(hash[numsToFind]);
                result.push_back(i);
                return result;
            }
            hash[nums[i]]=i;
        }
        return result;
    }
};
public class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map=new HashMap<>();
        for(int i=0;i<nums.length;i++){
            int numToFind=target-nums[i];
            if(map.containsKey(numToFind))  return new int[]{ map.get(numToFind),i};
            map.put(nums[i],i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

相关文章

网友评论

      本文标题:1. Two Sum两数之和

      本文链接:https://www.haomeiwen.com/subject/coellxtx.html