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.

  • 相关阅读:
    零位扩展和符号位扩展
    JAVA虚拟机20基于栈的解释器执行过程示例
    JAVA虚拟机16方法的动态调用
    JAVA虚拟机17栈帧(局部变量表操作数栈动态连接返回地址)
    JAVA虚拟机21JAVA内存模型
    JAVA虚拟机18方法调用
    符号扩展和零位扩展
    JAVA虚拟机22原子性、可见性与有序性、先行发生原则
    MYSQL各版本下载,包括linux和windows
    【转】Android模拟器怎么配置网络连通
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4773990.html
Copyright © 2011-2022 走看看