天天看點

(LeetCode)Java 求解兩數之和

文章目錄

    • 一、題解
    • 二、代碼
    • 三、總結

一、題解

給定一個整數數組 nums 和一個目标值 target,請你在該數組中找出和為目标值的那 兩個 整數,并傳回他們的數組下标。

你可以假設每種輸入隻會對應一個答案。但是,數組中同一個元素不能使用兩遍。

示例:

給定 nums = [2, 7, 11, 15], target = 9

因為 nums[0] + nums[1] = 2 + 7 = 9

是以傳回 [0, 1]

簡單的暴力解法就不做介紹了

本題可以借助哈希表,對于每一個數組中的元素 x ,可以借助哈希表中的

containsKey

判斷是否存在

target - x

,然後将 x 插入到哈希表中,保證不會讓 x 和自己比對

二、代碼

public class Test {
    public static void main(String[] args) {
        int[] a = {3, 4};
        int[] b = twoSum(a, 6);
        System.out.println(Arrays.toString(b));
    }

    public static int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; ++i) {
            if (map.containsKey(target - nums[i])) {
                //注意這裡傳回的是個數組
                return new int[]{map.get(target - nums[i]), i};
            }
            //注意這個入 map 操作隻能放這
            map.put(nums[i], i);
        }
        return new int[0];
    }
}
           

三、總結

(1)數組的初始化

int[] score = null;
score = new int[3];
等價于
int score[] = new int[10]; 
           
資料類型[] 數組名 = {初值0,初值1,....初值n}
例如:
int[] score = {32,45,67,90};
           
資料類型[][] 數組名 = new 資料類型[行的個數][列的個數];
示例:
int[][] score = new int[3][4];//聲明整型數組score,同時為其開辟一塊記憶體空間
           

(2)hashMap:無序存放,key 不允許重複

Map<String,String > map = new HashMap<String, String>();//執行個體化 map
//增加key-value
map.put("1","Java");
//根據 key 求出 value
String val = map.get("2");
//判斷是否存在 key-value
if (map.containsKey("1")) {
   System.out.println("搜尋的 key 存在!");
}
if (map.containsValue("Java")) {
   System.out.println("搜尋的 Value 存在!");
}
//輸出全部的key
Set<String > keys = map.keySet();//得到全部的 key
Iterator<String> iter = keys.iterator();
System.out.print("全部的 key:");
while (iter.hasNext()){
   String  str = iter.next();
   System.out.print(str + "、");
}
//輸出全部的value
Collection<String > values = map.values();//得到全部的 key
Iterator<String> iter = values.iterator();
System.out.print("全部的 value:");
while (iter.hasNext()){
    String  str = iter.next();
    System.out.print(str + "、");
}
//或者使用 foreach 輸出 Map 執行個體
for (Map.Entry<String ,String> me:map.entrySet()){//輸出 Set 集合
      System.out.println(me.getKey() + "-->" + me.getValue());
}
           

(3)這種輸出數組的方式很厲害:

//注意這裡傳回的是個數組
return new int[]{map.get(target - nums[i]), i};