两数之和

两数之和题目入口
方法一:暴力法,穷举所有两数组合,时间复杂度为O(\(n^2\))

public int[] twoSum(int[] nums, int target) {
        int len = nums.length;
        for(int i = 0; i < len - 1; i++){
            for(int j = i + 1; j < len; j++){
                if(nums[i] + nums[j] == target){
                    return new int[]{i , j};
                }
            }
        }
        //如果找不到答案,抛出异常
        throw new IllegalArgumentException("no solution");
}

方法二:哈希表存储所有数的信息,时间复杂度为O(\(n\))

public int[] twoSum(int[] nums, int target) {
        int len = nums.length;
        HashMap<Integer, Integer> hashMap = new HashMap<>();

        //1.遍历数组,将数据全部保存到hash表里面
        for(int i = 0; i < len; i++){
            hashMap.put(nums[i] , i);
        }

        //2.再次遍历数组,寻找每个数对应的那个数是否存在
        for(int i = 0; i < len; i++){
            int num = target - nums[i];//需要找到的值
            if(hashMap.containsKey(num) && hashMap.get(num) != i){
                return new int[]{i , hashMap.get(num)};
            }
        }

        //如果找不到答案,抛出异常
        throw new IllegalArgumentException("no solution");
}

方法三:遍历一次哈希表,时间复杂度为O(\(n\))

public int[] twoSum(int[] nums, int target) {
        int len = nums.length;
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        //遍历数组,寻找每个数对应的那个数是否存在(向前寻找)
        for(int i = 0; i < len; i++){
            int num = target - nums[i];//需要找到的值
            if(hashMap.containsKey(num) && hashMap.get(num) != i){
                return new int[]{hashMap.get(num) , i};
            }
            hashMap.put(nums[i] , i);
        }
        //如果找不到答案,抛出异常
        throw new IllegalArgumentException("no solution");
}
posted @ 2021-06-03 21:32  小布丁超级帅  阅读(66)  评论(0)    收藏  举报