Two Sum

作者: EIP_Miracle | 来源:发表于2017-10-21 22:48 被阅读0次

    Description:

    Given an array of integers, return the indices of the two numbers such that they add up to a specific target. You mat 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,元素的index存为value, 那么就可以利用map.containsKey()的方法找map中是否存在target-nums[i],也就是与当前元素匹配的结果,这是判断两者的index是不是一样,不一样则可以输出,因为题目中假设只有一个解。

    Solution

    class solution{
      public static int[] twoSum(int[] nums, int target){
        Map<Integer, Integer> map = new HashMap<>();
        int len = nums.length;
        for(int i = 0; i < len; i++){
          map.put(nums[i], i);
        }
        for(int j = 0; j < len; j++){
          int complement = target - nums[i];
          if(map.containsKey(complement) && map.get(complement) != i){
            return new int[] {i, map.get(complement)}
          }
        }
        return new IllegalArgumentException("No two sum soluton");
      }
    }
    

    相关文章

      网友评论

        本文标题:Two Sum

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