算法(三)--leetcode两数之和

前言

仅记录学习笔记,如有错误欢迎指正。

题目

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素

示例

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

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

解法一

直接两次for循坏遍历 找出两个值和下标
时间复杂度:O(n^2),空间复杂度:O(1),

 public int[] twoSum1(int[] arr, int target) {
    
    

        for (int i = 0; i < arr.length; i++) {
    
    
            for (int j = i + 1; j < arr.length; j++) {
    
    
                if (arr[i] == target - arr[j]) {
    
    
                    return new int[]{
    
    i, j};
                }
            }

        }
        throw new RuntimeException("没有两数和为target的值");

解法二

以空间换时间,两遍hash表
时间复杂度:O(n),空间复杂度:O(n),

 public int[] twoSum2(int[] arr, int target) {
    
    
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
    
    
            map.put(arr[i], i);
        }
        for (int i = 0; i < arr.length; i++) {
    
    
            int temp = target - arr[i];
            if (map.containsKey(temp) && map.get(temp) != i) {
    
    
                return new int[]{
    
    i, map.get(temp)};
            }
        }
        throw new RuntimeException("没有两数和为target的值");

    }

解法三

在解法二的基础上 再优化一点

public int[] twoSum3(int[] arr, int target) {
    
    
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
    
    
            int temp = target - arr[i];
            if (map.containsKey(temp)) {
    
    
                return new int[]{
    
    i, map.get(temp)};
            }
            map.put(arr[i], i);
        }
        throw new IllegalArgumentException("没有两数和为target的值");
    }

猜你喜欢

转载自blog.csdn.net/njh1147394013/article/details/112257057