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;
        }
    }
    

      

  • 相关阅读:
    尝试用Gearman实现分布式处理(PHP)
    如何在ubuntu上安装node.js
    Linux crontab定时执行任务 命令格式与详细例子
    MySQL的information_schema
    Ubuntu安装MongoDB
    Log4j日志管理系统简单使用说明
    android:screenOrientation横屏竖屏设置
    Android 自定义progressBar样式
    Java使用JDOM解析XML(转载,简单又详细)
    Caused by: android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity
  • 原文地址:https://www.cnblogs.com/guozhiguoli/p/3338505.html
Copyright © 2011-2022 走看看