zoukankan      html  css  js  c++  java
  • Two Sum 解答

    Question:

    Given an array of integers, find two numbers such that they add up to a specific target number.

    The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

    You may assume that each input would have exactly one solution.

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2

    Solution:

    1. O(n2) runtime, O(1) space – Brute force:

    The brute force approach is simple. Loop through each element x and find if there is another value that equals to target – x. As finding another value requires looping through the rest of array, its runtime complexity is O(n2).

    2. O(n) runtime, O(n) space – Hash table:

    We could reduce the runtime complexity of looking up a value to O(1) using a hash map that maps a value to its index.

     1 public class Solution {
     2     public int[] twoSum(int[] nums, int target) {
     3         Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
     4         int[] result = new int[2];
     5         int length = nums.length;
     6         for (int i = 0; i < length; i++) {
     7             int left = target - nums[i];
     8             if (hm.get(left) != null) {
     9                 result[0] = hm.get(left) + 1;
    10                 result[1] = i + 1;
    11             } else {
    12                 hm.put(nums[i], i);
    13             }
    14         }
    15         return result;
    16     }
    17 }

    3. O(nlogn) runtime, O(1) space - Binary search

    Similar as solution 1, but use binary search to find index2.

    4. O(nlogn) runtime, O(1) space - Two pointers

    First, sort the array in ascending order vwhich uses O(nlogn).

    Then, right pointer starts from biggest number and left pointer starts from smallest number. If two sum is greater than the target number, move the right pointer. If two sum is smaller than the target number, move the left pointer.

  • 相关阅读:
    EL 自定义函数
    Linux 软件安装管理
    Linux 网络环境查看命令
    Linux 用户和用户组的命令
    Linux 用户和用户组进阶命令
    Linux 用户和用户组的基本命令
    将博客搬至CSDN
    U盘做系统启动盘(PE)时的文件格式选择 HDD ZIP FDD
    STM32 的几种输入输出模式
    define 中强制类型转换 && 浮点数后面带f
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4773990.html
Copyright © 2011-2022 走看看