美文网首页
001. Two Sum

001. Two Sum

作者: 海湾码农 | 来源:发表于2016-03-13 18:43 被阅读0次

    Given an array of integers, return indices of the two numbers such that they add up to a specific target.

    Given nums = [2, 7, 11, 15], target = 9,
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].
    

    使用HashMap存储数字,对每一个元素,查找target-nums[i]元素对应的下标,如果找到则返回结果。

    java code:

    public class Solution {
      public int[] twoSum(int[] nums, int target) {
        HashMap map = new HashMap<Integer, Integer>();
        int[] result = new int[2];
        
        for (int i = 0; i < nums.length; i++) {
          Integer number = (Integer)map.get(nums[i]);
          if (number == null) map.put(nums[i], i);
            
          number = (Integer) map.get(target - nums[i]);
            
          if (number != null && number != i) {
            result[0] = number;
            result[1] = i;
            return result;
          }  
        }
        return result;
      }
    }

    相关文章

      网友评论

          本文标题:001. Two Sum

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