LeetCode Two Sum
2014-09-13 11:13
267 查看
题目描述:https://oj.leetcode.com/problems/two-sum/
题目大意:给定一个数组,一个target 数,找出数组中的两个数a,b,满足a+b=target。返回a,b的下标,且a的下标小于b的下标。
package TwoSum;
import java.util.Arrays;
public class Solution {
class Number implements Comparable<Number>{
int pos;
int num;
Number(int num,int pos){
this.num = num;
this.pos = pos;
}
@Override
public int compareTo(Number arg0) {
if(this.num<arg0.num) return -1;
else
if(this.num>arg0.num) return 1;
return 0;
}
}
public int[] twoSum(int[] numbers,int target){
Number[] num_pos = new Number[numbers.length];
for(int i=0;i<numbers.length;i++)
num_pos[i] = new Number(numbers[i],i);
Arrays.sort(num_pos);
int[] ans = new int[2];
for(int i=0;i<num_pos.length;i++){
int temp = target - num_pos[i].num;
Number tar = new Number(temp,-1);
int index = Arrays.binarySearch(num_pos,i+1,num_pos.length,tar);
if(index>=0){
ans[0] = num_pos[i].pos+1;
ans[1] = num_pos[index].pos+1;
if(ans[0]>ans[1]){
int t = ans[0];
ans[0] = ans[1];
ans[1] = t;
}
}
}
return ans;
}
}
题目大意:给定一个数组,一个target 数,找出数组中的两个数a,b,满足a+b=target。返回a,b的下标,且a的下标小于b的下标。
package TwoSum;
import java.util.Arrays;
public class Solution {
class Number implements Comparable<Number>{
int pos;
int num;
Number(int num,int pos){
this.num = num;
this.pos = pos;
}
@Override
public int compareTo(Number arg0) {
if(this.num<arg0.num) return -1;
else
if(this.num>arg0.num) return 1;
return 0;
}
}
public int[] twoSum(int[] numbers,int target){
Number[] num_pos = new Number[numbers.length];
for(int i=0;i<numbers.length;i++)
num_pos[i] = new Number(numbers[i],i);
Arrays.sort(num_pos);
int[] ans = new int[2];
for(int i=0;i<num_pos.length;i++){
int temp = target - num_pos[i].num;
Number tar = new Number(temp,-1);
int index = Arrays.binarySearch(num_pos,i+1,num_pos.length,tar);
if(index>=0){
ans[0] = num_pos[i].pos+1;
ans[1] = num_pos[index].pos+1;
if(ans[0]>ans[1]){
int t = ans[0];
ans[0] = ans[1];
ans[1] = t;
}
}
}
return ans;
}
}
相关文章推荐
- 【Leetcode】Two Sum
- LeetCode 1 Two Sum
- leetcode -- Two Sum
- leetcode_1. Two Sum
- Leetcode习题: Two Sum
- LeetCode 1 - Two Sum
- leetcode-- two sum
- Leetcode 1. Two Sum
- Leetcode8 Two sum
- [Leetcode]Two Sum
- [leetcode-1] Two sum
- leetcode 46: Two Sum
- LeetCode1_Two Sum
- LeetCode 167 Two Sum 2-Input array is sorted
- leetcode: Two Sum
- LeetCode(62)-Two Sum
- 【leetcode】Two Sum
- [Leetcode] Two Sum
- [Leetcode] Two Sum
- [LeetCode]-001-Two Sum