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⊙)嗯。

  • 相关阅读:
    redis在centos7下安装(源码编译)
    Centos7之Gcc安装
    Jmeter工具之上传图片,上传音频文件接口
    什么是系统平均负载(Load average)
    sonar+Jenkins 构建代码质量自动化分析平台
    数据库主从相关配置参数说明
    现有数据库配置主从同步
    MySQL5.7多主一从(多源复制)同步配置
    MySQL5.7主从从配置
    MySQL5.7主从同步配置
  • 原文地址:https://www.cnblogs.com/zhouyee/p/4429253.html
Copyright © 2011-2022 走看看