zoukankan      html  css  js  c++  java
  • 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

    一开始用C语言写,做了两次遍历,发现时间超限,查了下说是O(n^2)的不行,改成下面这个,还是运行时间出错。

     1 int* twoSum(int numbers[], int n, int target) {
     2     int num[10000],i,add[10000];
     3     for(i=0;i<n;i++){
     4     num[numbers[i]]=numbers[i];
     5     add[numbers[i]]=i;}
     6     int index1,m;
     7     int index[2];
     8     for(index1=0;index1<n;index1++)
     9     {
    10         m=target-numbers[index1];
    11             if(num[m]==m)
    12            {
    13                index[0]=index1+1;
    14                index[1]=add[m]+1;
    15                return index;
    16            }
    17         }
    18     }

    不知道为什么,上面的应该是O(n)了。最后用了hashtable,Java编写,AC了。

     1 public static int[] twosum

    (int[] numbers,int target){
     2         int[]r=new int[2];
     3         Hashtable<Integer,Integer> nums=new Hashtable<Integer,Integer>();
     4         for(int i=0;i<numbers.length;i++)
     5         {
     6             nums.put(numbers[i], i);
     7         }
     8         for(int i = 0;i<numbers.length;i++)
     9         {
    10             Integer m=nums.get(target-numbers[i]);
    11             if(m!=null&&m!=i)
    12             {
    13                 r[0]=i+1;
    14                 r[1]=m+1;
    15                 return r;
    16             }
    17         }
    18         return r;
    19         
    
    
    20 }

    AC后给出的solution

    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).

    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.

    运行时间比较,总听人说Java效率低,(⊙v⊙)嗯。

  • 相关阅读:
    3年度研发项目情况项目目标文档
    2系统利益相关者描述案例
    讨论结果
    本学期《软件需求分析》需要掌握的内容(个人总结)
    第二周进度条
    四则运算
    第一周进度记录
    java web
    ke tang zuo ye
    2015-05-26 随笔
  • 原文地址:https://www.cnblogs.com/zhouyee/p/4429253.html
Copyright © 2011-2022 走看看