兩數之和(力扣)


import java.util.HashMap;

public class Test {
    public static void main(String[] args) {
        int[] arr = new int[]{2,7,11,15};
        int target = 9;
        System.out.println(test1(arr,target));
        System.out.println(test2(arr,target));
    }

    //雙迭代數組,時間複雜度n*2
    public static String test1(int[] nums, int target) {
        for (int i = 0; i < nums.length - 1; i++) {
            for (int j = i + 1;j < nums.length ;j++){
                if (nums[i] + nums[j] == target)
                    return "[" + i + "," + j +"]";
            }
        }
        return "No two sum solution";
    }

    //用hashmap存源數組,時間複雜度n,空間複雜度n,用空間換時間。
    public static String test2(int[] nums, int target) {
        HashMap<Integer,Integer> hashMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            hashMap.put(nums[i],i);
        }
        for (int i = 0; i < nums.length; i++) {
            int temp = target - nums[i];
            if (hashMap.containsKey(temp) && hashMap.get(temp) != i){//確保數字不被用兩次
                return "[" + i + "," + hashMap.get(temp) +"]";
            }
        }
        return "No two sum solution";
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章