1 Two Sum

2019-04-19  本文已影响0人  Mree111

Find two numbers in the list so the sum can match the target number.

Solution

  1. 最简单的brute force可以O(N^2)解决
    2.使用Hash Table直接做查询
class Solution {
    public int[] twoSum(int[] nums, int target) {
           Map<Integer,Integer> map = new HashMap<>();
            for(int i=0;i<nums.length;i++){
                int other=target - nums[i];
                if(map.containsKey(other))
                    return new int[] {map.get(other),i};
                
                map.put(nums[i],i);
            }
         throw new IllegalArgumentException("No two sum solution");
    }
}```
上一篇 下一篇

猜你喜欢

热点阅读