博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode: Two Sum
阅读量:6205 次
发布时间:2019-06-21

本文共 5402 字,大约阅读时间需要 18 分钟。

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
twoSum(vector
&numbers, int target) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 vector
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
twoSum(vector
&numbers, int target) {17 // Start typing your C/C++ solution below18 // DO NOT write int main() function19 vector
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
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 else41 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
{ 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; } }

 

转载于:https://www.cnblogs.com/pengzheng/archive/2013/05/12/3074624.html

你可能感兴趣的文章
Nginx+Php(FastCGI、Php-fpm)+Mysql+Zend+Memcache+Phpmyadmin+MongoDB+TT安装
查看>>
CentOS下Samba文件服务器的安装与配置
查看>>
C# 线程间不能调用剪切板的问题
查看>>
a标签实现不跳转点击
查看>>
在VS2012中实现Ext JS的智能提示太简单了
查看>>
ChemDraw教程:如何查看和删除俗名
查看>>
深入理解javascript原型和闭包(7)——原型的灵活性
查看>>
LOL游戏程序中对一些函数的Hook记录(Win10 x64)
查看>>
【Python】list和tuple 区别比较
查看>>
C语言可变参数
查看>>
给你的Mr.Right画张择偶地图像
查看>>
病毒式推广最终可能会走到尽头
查看>>
VMware vSphere简介
查看>>
django时间问题和时区设置
查看>>
ORA-01555 原因与解决
查看>>
数据库笔记2:SQL运算符
查看>>
中小企业如何提高售前,售中,售后客服质量?
查看>>
通过传id封装loading
查看>>
OpenStack创建win7实例遇到的问题(尚未解决,求帮助)
查看>>
Mysql-my-innodb-heavy-4G.cnf配置文件注解
查看>>