Last active
December 11, 2015 15:09
-
-
Save guolinaileen/4619080 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
class Solution { | |
public: | |
class Pair | |
{ | |
public: | |
int index; | |
int val; | |
Pair(int i, int v) | |
{ | |
index=i; | |
val=v; | |
} | |
}; | |
class less_than_key | |
{ | |
public: | |
const bool operator() (const Pair & a, const Pair& b) | |
{ | |
return (a.val < b.val); | |
} | |
}; | |
vector<int> twoSum(vector<int> &numbers, int target) { | |
// Start typing your C/C++ solution below | |
// DO NOT write int main() function | |
vector<int> result; | |
int length=numbers.size(); | |
vector<Pair> pairs; | |
for(int i=0; i<length; i++) | |
{ | |
pairs.push_back(Pair(i+1, numbers[i])); | |
} | |
sort(pairs.begin(), pairs.end(), less_than_key()); | |
int start=0, end=length-1; | |
while(start<end) | |
{ | |
int temp=pairs[start].val + pairs[end].val; | |
if(temp==target) | |
{ | |
result.push_back(pairs[start].index); | |
result.push_back(pairs[end].index); | |
break; | |
} | |
if(temp<target) start++; | |
if(temp>target) end--; | |
} | |
sort(result.begin(), result.end()); | |
return result; | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
class Pair | |
{ | |
int index; | |
int val; | |
Pair(int i, int v) | |
{ | |
index=i; | |
val=v; | |
} | |
} | |
public int[] twoSum(int[] numbers, int target) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
Pair pairs[]=new Pair[numbers.length]; | |
int result[]=new int[2]; | |
for(int i=0; i<numbers.length; i++) | |
{ | |
pairs[i]=new Pair(i+1, numbers[i]); | |
} | |
Arrays.sort(pairs, PARI_ORDER); | |
int start=0, end=numbers.length-1; | |
while(start<end) | |
{ | |
int temp=pairs[start].val+pairs[end].val; | |
if(temp==target) | |
{ | |
result[0]=pairs[start].index; | |
result[1]=pairs[end].index; | |
break; | |
} | |
if(temp>target) end--; | |
if(temp<target) start++; | |
} | |
Arrays.sort(result); | |
return result; | |
} | |
public static final Comparator<Pair> PARI_ORDER=new Comparator<Pair>() | |
{ | |
public int compare(Pair i, Pair j) | |
{ | |
return new Integer(i.val).compareTo(new Integer(j.val)); | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment