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

  • 相关阅读:
    UNITY 多个子MESH与贴图的对应关系
    UNITY 优化之带Animator的Go.SetActive耗时问题,在手机上,这个问题似乎并不存在,因为优化了后手机上运行帧率并未明显提升
    发现一个好办法-有问题可以到UNITY论坛搜索
    静态函数造成GC的原因
    关于GC.Collect在不同机器上表现不一致问题
    VULKAN学习资料收集
    Array.Resize(ref arry, size);
    玩游戏消耗精力
    浮点数与定点数问题
    P8 Visible Lattice Points
  • 原文地址:https://www.cnblogs.com/zhouyee/p/4429253.html
Copyright © 2011-2022 走看看