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存儲數(shù)字,對每一個元素,查找target-nums[i]元素對應(yīng)的下標,如果找到則返回結(jié)果。

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;
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Given an array of integers, return indices of the two num...
    周肅閱讀 284評論 0 0
  • Problem description Given an array of integers, return in...
    QyQiaoo閱讀 133評論 0 0
  • 韓雪怎么也沒想到會在自己27歲的時候因為一個男人而逃離生活了多年的城市。 對,不是跟著他走,而是落魄的逃離。 如今...
    韓冬冬閱讀 676評論 14 6
  • 搜索是在一個項目集合中找到一個特定項目的算法過程。搜索通常的答案是真的或假的,因為該項目是否存在。 搜索的幾種常見...
    LittlePy閱讀 464評論 0 0
  • 你的背影,你的側(cè)臉,你的笑臉。 都近在咫尺,我伸手就可以觸摸到。 車外美麗的景色,一掃而過。 陽光照著你的剪影,一...
    stefx閱讀 175評論 0 0

友情鏈接更多精彩內(nèi)容