• LeetCode: Two Sum


    http://leetcode.com/onlinejudge#question_1

    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

    JAVA版答案:

    两个for循环,O(N^2).需要改进 Judge Small 496 milli secs, Judge Large 540 milli secs.n不大的时候这样很好。

     1 public class Solution {
     2     public int[] twoSum(int[] numbers, int target) {
     3         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         int[] arr = new int[2]; 
     6         for (int i = 0; i <= numbers.length - 2; ++i) {
     7             for (int j = i + 1; j <= numbers.length - 1; ++j) {
     8                 if (numbers[i] + numbers[j] == target) {
     9                         arr[0] = i + 1;
    10                         arr[1] = j + 1;
    11                         break;
    12                 }
    13             }
    14         }  
    15         return arr; 
    16     }
    17 }

    从今天开始做leetcode准备找饭碗混口饭吃免得饿死了。。。

    C++版答案:

    两个for循环,O(N^2).需要改进 Judge Small 16 secs, Judge Large 52 milli secs.

     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int> &numbers, int target) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         vector<int> ivct;
     7         for (int i = 0; i <= numbers.size() - 2; ++i) {
     8             for (int j = i + 1; j <= numbers.size() - 1; ++j) {
     9                 if (numbers[i] + numbers[j] == target) {
    10                         ivct.push_back(i + 1);
    11                         ivct.push_back(j + 1);
    12                         break;
    13                 }
    14             }
    15         }
    16         return ivct; 
    17     }
    18 };

     C++改进:先排序o(nlogn),在头尾往中间找o(n) Judge Smal 8 milli secs, Judge Large 12 milli secs.这显然是最高效的算法了,速度大大提升。

     1 struct Node
     2   {
     3       int val;
     4       int index;
     5       Node(){}
     6       Node(int v, int idx):val(v), index(idx){}
     7   };
     8 
     9   bool compare(const Node &lhs, const Node &rhs)
    10   {
    11       return lhs.val < rhs.val;
    12   }
    13 
    14   class Solution {
    15   public:
    16       vector<int> twoSum(vector<int> &numbers, int target) {
    17           // Start typing your C/C++ solution below
    18           // DO NOT write int main() function
    19           vector<Node> a;
    20           for(int i = 0; i < numbers.size(); i++)
    21               a.push_back(Node(numbers[i], i + 1));
    22           sort(a.begin(), a.end(), compare);
    23 
    24           int i = 0;
    25           int j = numbers.size() - 1;
    26           while(i < j)
    27           {
    28               int sum = a[i].val + a[j].val;
    29               if (sum == target)
    30               {
    31                   vector<int> ret;
    32                   int minIndex = min(a[i].index, a[j].index);
    33                   int maxIndex = max(a[i].index, a[j].index);
    34                   ret.push_back(minIndex);
    35                   ret.push_back(maxIndex);
    36                   return ret;
    37               }
    38               else if (sum < target)
    39                   i++;
    40               else
    41                   j--;
    42           }
    43       }
    44   };

     JAVA改进,nlogn,(已验证)Judge Small 556 milli secs,Judge Large 524 milli secs......与原版相比,小数据更慢,大数据更快,因为这是对n很大时候的高效算法。

    import java.util.Arrays;
     
     //author:pz
     
     /* 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.
      */
     
     class Node implements Comparable<Node> {
         private int val;
         private int index;
     
         Node(int v, int idx) {
             setVal(v);
             setIndex(idx);
         }
     
         public int getVal() {
             return this.val;
         }
     
         public void setVal(int val) {
             this.val = val;
         }
     
         public int getIndex() {
             return index;
         }
     
         public void setIndex(int index) {
             this.index = index;
         }
     
         @Override
         public int compareTo(Node o) {
             // TODO Auto-generated method stub
             return this.getVal() - o.getVal();
         }
     
         public String toString() {
             return Integer.toString(getVal());
         }
     }
     
    public class Solution {
         public int[] twoSum(int[] numbers, int target) {
             int[] ret = new int[2];
             Node[] a = new Node[numbers.length];
             for (int i = 0; i < numbers.length; i++) {
                 a[i] = new Node(numbers[i], i + 1);
             }
             Arrays.sort(a);
             int i = 0, j = a.length - 1;
             LABLE: while (i < j) {
                 int sum = a[i].getVal() + a[j].getVal();
                 if (sum == target) {
                     ret[0] = Math.min( a[i].getIndex(), a[j].getIndex());
                     ret[1] = Math.max( a[i].getIndex(), a[j].getIndex());
                     break LABLE;
                 } else if (sum < target)
                     ++i;
                 else
                     --j;
             }
             return ret;
         }
     }
  • 相关阅读:
    POJ 2407 Relatives 欧拉函数
    HDU 4704 Sum 超大数幂取模
    HDU 4699 Editor 维护栈
    HDU 4696 Answers 水题
    HDU 4686 Arc of Dream 矩阵
    [转]高斯消元题集
    [转]计算几何题集
    POJ 2981 Strange Way to Express Integers 模线性方程组
    Linux 设置文件默认打开方式
    FZU 1402 猪的安家 中国剩余定理
  • 原文地址:https://www.cnblogs.com/pengzheng/p/3074624.html
Copyright © 2020-2023  润新知