大学学了一堆理论,编码水平渣。果然应该刷刷题了。
正好最近看java ,试着就java写一写。
水平略渣。。
题目:
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
代码:1
public static int[] twoSum(int[] numbers, int target) {
int[] temp = (int[]) numbers.clone();
Arrays.sort(numbers);
int []index = new int[2];
int length = numbers.length;
int left = 0;
int right = length-1;
int sum = 0;
int tt = 0;
int pp = 0;
while(left < right)
{
sum = numbers[left]+numbers[right];
if(sum == target)
{
for(int i = 0;i<length;i++)
{
if(temp[i] == numbers[left]&&tt==0)
{
index[0] = i+1;
tt = 1;
}
else if(temp[i] == numbers[right]&&pp==0)
{
index[1] = i+1;
pp = 1;
}
if(pp==1&&tt==1)
{
if(index[0]>index[1])
{
int t = index[0];
index[0] = index[1];
index[1] = t;
return index;
}
}
}
return index;
}
else if(sum < target)
{
left++;
}
else
right--;
}
return index;
}
public static void main(String[] args) {
int []numbers ={-1,-2,-3,-4,-5};
int []index = new int[2];
index = twoSum(numbers,-8);
System.out.print(index[0]+"\t\t\t\t"+index[1]);
}
代码:2
public class hello {
public static int[] twoSum(int[] numbers, int target) {
int[] temp = (int[]) numbers.clone();
Arrays.sort(numbers);
int []index = new int[2];
int length = numbers.length;
int left = 0;
int right = length-1;
int sum = 0;
// int tt = 0;
// int pp = 0;
ArrayList<Integer> in = new ArrayList();
while(left < right)
{
sum = numbers[left]+numbers[right];
if(sum == target)
{
for(int i = 0;i<length;i++)
{
if(temp[i] == numbers[left])
{
in.add(i+1);
}
else if(temp[i] == numbers[right])
{
in.add(i+1);
}
if(in.size()==2)
{
break;
}
}
break;
}
else if(sum < target)
{
left++;
}
else
right--;
}
index[0] = in.get(0);
index[1] = in.get(1);
return index;
}
public static void main(String[] args) {
int []numbers ={-1,-2,-3,-4,-5};
int []index = new int[2];
index = twoSum(numbers,-8);
System.out.print(index[0]+"\t\t\t\t"+index[1]);
}
}