zoukankan      html  css  js  c++  java
  • 【LeetCode】3. Two Sum

    从头开始做起吧,省得自己挑肥拣瘦。虽然网上有很多leetcode的解题报告了,自己写写还是能够加深记忆。

    ---------Two Sum

    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

    1、O(n2) 能够简单解出,注意index从1开始。

    2、O(n*log(n)) 先排序再左右往中间遍历: 本来想把target值放进数组中排序,再取比target值小的部分从两边到中间遍历。这样在遍历前得先找到target值的下标。+O(n)这样优化程序不高,而且题中说的是integer,不一定是non-negative,出现负数这种办法就错了。

    不想要下面代码最后的那趟遍历,可以用数据结构,排序时记录索引号,空间复杂度O(n),最后要注意比较index的大小。

    import java.util.Arrays;
     
    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
            // Start typing your Java solution below
            // DO NOT write main() function
         assert numbers != null && numbers.length > 1;   int[] result = new int[2]; int[] tmp = new int[numbers.length]; for (int i = 0; i < numbers.length; i++) { tmp[i] = numbers[i]; } Arrays.sort(tmp); int l = 0; int r = tmp.length - 1; int sum = tmp[l] + tmp[r]; while( sum != target && r > l) { if (sum > target) { r--; } else { l++; } sum = tmp[l] + tmp[r]; } int index = 0; for (int i = 0; i < numbers.length; i++) { if (tmp[l] == numbers[i] || tmp[r] == numbers[i]) { result[index] = i + 1; index++; if (index > 1) break; } } return result; } }

    3、O(n) Hash,需要额外的O(n)空间开销

    import java.util.HashMap;
     
    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
            // Start typing your Java solution below
            // DO NOT write main() function
            int[] result = new int[2];
            HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
            for (int i = 0; i < numbers.length; i++)
            {
                if (map.containsKey(target - numbers[i]))
                {
                    result[0] = map.get(target-numbers[i]) + 1;
                    result[1] = i + 1;
                    break;
                }
                else
                {
                    map.put(numbers[i], i);
                }
            }
             
            return result;
        }
    }
    

      

  • 相关阅读:
    T4文本模板转换过程
    ARKit从入门到精通(6)-ARSession介绍
    ARKit从入门到精通(5)-ARScnView介绍
    ARKit从入门到精通(4)-ARKit全框架API大全
    ARKit从入门到精通(3)-ARKit自定义实现
    ARKit从入门到精通(2)-ARKit工作原理及流程介绍
    ARKit从入门到精通(1)-ARKit初体验
    ios系统中各种设置项的url链接
    iOS 检测网络状态 自动判断 认为提示网络改变
    ios 根据scrollview滑动的偏移计算滑动到第几页算法(不同需求不同计算)
  • 原文地址:https://www.cnblogs.com/guozhiguoli/p/3338505.html
Copyright © 2011-2022 走看看