[力扣算法题] TwoSum(两数之和)


方法一:暴力穷举所有两数之和

代码如下:


    //方法一:暴力法,穷举所有两数组合
    public int[] twoSum(int[] nums, int target) {
        //双重for循环实现
        int n = nums.length;
        System.out.println("n:" + n);
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1; j < n; j++) {
                if (nums[i]+nums[j] == target){
                    return new int[]{i,j};
                }
            }
        }
        //如果找不到,抛出异常
        throw new RuntimeException("找不到解");
    }

方法二:保存所有数字的信息

    public int[] twoSum2(int[] nums, int target) {
        int n = nums.length;
        HashMap<Integer, Integer> map = new HashMap<>();

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

        //2.再次遍历数组,寻找每个数对应的那个数是否存在
        for (int i = 0; i < n; i++){
            int thatNum = target - nums[i];
            //如果那个数存在,直接返回结果,并且不是当前数自身
            if (map.containsKey(thatNum) && map.get(thatNum) != i){
                //自己返回
                return new int[]{i, map.get(thatNum)};
            }
        }
        throw new RuntimeException("找不到解");
    }


分类:Java
标签: 算法
文章目录