001. Two Sum

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;
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Given an array of integers, return indices of the two num...
    周肃阅读 275评论 0 0
  • Problem description Given an array of integers, return in...
    QyQiaoo阅读 109评论 0 0
  • 韩雪怎么也没想到会在自己27岁的时候因为一个男人而逃离生活了多年的城市。 对,不是跟着他走,而是落魄的逃离。 如今...
    韩冬冬阅读 610评论 14 6
  • 搜索是在一个项目集合中找到一个特定项目的算法过程。搜索通常的答案是真的或假的,因为该项目是否存在。 搜索的几种常见...
    LittlePy阅读 448评论 0 0
  • 你的背影,你的侧脸,你的笑脸。 都近在咫尺,我伸手就可以触摸到。 车外美丽的景色,一扫而过。 阳光照着你的剪影,一...
    stefx阅读 168评论 0 0