1. 程式人生 > 其它 >leetcode 兩數之和 java

leetcode 兩數之和 java

給定一個整數陣列 nums 和一個目標值 target,請你在該陣列中找出和為目標值的那 兩個 整數,並返回他們的陣列下標。

你可以假設每種輸入只會對應一個答案。但是,你不能重複利用這個陣列中同樣的元素。

示例:

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

因為 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
第一種是冒泡查詢,但不能是同一個數字;

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] a = new int[2];
        for(int i = 0; i < nums.length; i++){
            int res = target - nums[i];
                for(int j = 0; j < nums.length; j++){
                    if(res ==nums[ j] && i != j){
                        a[0] = i;
                        a[1] = j;
                        return a;
                    }
                }
        }
        return a;
    }
}

第二種:用Hash
為了使得程式碼的複雜度降低,我們可以採取第二種形式,是通過java中的hashmap 的方法,在這裡無基礎的也將可以使用hashmap 的用法Map <Integer,Integer> map = new HashMap<>();

map.put 是將鍵值推入
map.containsKey 是找到值,
而map.get 是獲取鍵

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