zoukankan      html  css  js  c++  java
  • 两数之和 Two Sum

    给定一个整数数列,找出其中和为特定值的那两个数。

    你可以假设每个输入都只会有一种答案,同样的元素不能被重用。

    示例:

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

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

    方法一


    使用i,j遍历数组nums中的每一个变量,验证nums[i]+nums[j]是否等于target

    代码如下:

        public static int[] twoSum(int[] nums, int target) {
    
            int N = nums.length;
    
            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};
    
            return null;
        }

    此方法的复杂度为O(N^2)

    方法二

    使用HashMap存储nums的值及对应的下标

    定义变量c=target-nums[i],在map中寻找是否存在键值为c

    代码如下:

        public static int[] twoSumMap(int[] nums, int target) {
    
            int N = nums.length;
            Map<Integer, Integer> map = new HashMap<>();
    
            // nums的值为key,下标为value
            for (int i=0; i<N; i++)
                map.put(nums[i], i);
    
            for (int i=0; i<N-1; i++) {
    
                int complement = target - nums[i];
                // 找到的键值不能为i
                if (map.containsKey(complement) && map.get(complement)!=i)
                    return new int[] {i, map.get(complement)};
            }
            return null;
        }

    复杂度分析:

    将nums存入map中,空间复杂度O(N)

    for循环寻找两个下标,时间复杂度为O(N)

    该方法中,键值为数组值,value为数组下标,故数组中数值相等的元素在map中只存储了一次。

    如nums[] = {2, 5, 5, 6}, map中为2-0, 5-2, 6-3,但这并不影响该算法找到正确的答案

    另外,若数组nums为有序的,则可以使用两个指针分别指向数组的首尾两个元素。

    比较两个元素的和与target,根据比较结果移动指针,直到两指针相遇或找到结果

    实现代码如下:

        public static int[] twoSumOrder(int[] nums, int target) {
    
            int i = 0;
            int j = nums.length - 1;
    
            while (i != j) {
    
                if (nums[i] + nums[j] == target)
                    return new int[] {i,j};
                else if (nums[i] + nums[j] > target)
                    j--;
                else
                    i++;
            }
    
            return null;
        }

    复杂度为O(N)

  • 相关阅读:
    我爱Java系列之---【SpringBoot打成war包部署】
    279. Perfect Squares
    矩阵dfs--走回路
    112. Path Sum
    542. 01 Matrix
    106. Construct Binary Tree from Inorder and Postorder Traversal
    105. Construct Binary Tree from Preorder and Inorder Traversal
    Invert Binary Tree
    563 Binary Tree Tilt
    145 Binary Tree Postorder Traversal
  • 原文地址:https://www.cnblogs.com/deltadeblog/p/8688283.html
Copyright © 2011-2022 走看看