1 Two Sum

作者: Mree111 | 来源:发表于2019-04-19 23:51 被阅读0次

    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");
        }
    }```

    相关文章

      网友评论

          本文标题:1 Two Sum

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