Leetcode刷題Java1. 兩數之和

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

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

示例:

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

因爲 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/two-sum
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

class Solution {
        public int[] twoSum(int[] nums, int target) {
//            return twoSumI(nums, target);
//            return twoSumII(nums, target);
            return twoSumIII(nums, target);
        }

        //方法三:使用Hash表,一重循環
        private int[] twoSumIII(int[] nums, int target) {
            Map<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < nums.length; i++) {
                if (map.containsKey(target - nums[i])) {
                    return new int[]{map.get(target - nums[i]), i};
                } else {
                    map.put(nums[i], i);
                }
            }
            throw new IllegalArgumentException("No two sum solution");
        }

        //方法二:使用Hash表,遍歷兩次
        //1.遍歷數組,利用hashmap保存數據中的元素,key爲nums[i],value爲i
        //2.遍歷數組,判斷hashmap中是否存在元素key爲target - nums[i],存在則返回索引值
        //注意:目標元素不能是 nums[i]本身!
        private int[] twoSumII(int[] nums, int target) {
            Map<Integer, Integer> map = new HashMap<>();
            for (int i = 0; i < nums.length; i++) {
                map.put(nums[i], i);
            }
            for (int i = 0; i < nums.length; i++) {
                int complament = target - nums[i];
                if (map.containsKey(complament) && map.get(complament) != i) {
                    return new int[]{i, map.get(complament)};
                }
            }
            throw new IllegalArgumentException("No two sum solution");
        }

        //方法一:暴力法,兩重循環
        private int[] twoSumI(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 new int[]{i, j};
                    }
                }
            }
            throw new IllegalArgumentException("No two sum solution");
        }
    }

 

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