58,452
社区成员
发帖
与我相关
我的任务
分享
public class leetcode001 {
static int[] nums= {-10,-1,-18,-19};
static int target = -19;
// static int[] nums= {3,2,4};
// static int target = 6;
// static int[] nums= {3,3};
// static int target = 6;
public static void main(String[] args) {
Solution a = new Solution();
int[] result = a.twoSum(nums, target);
System.out.println(result[0]);
System.out.println(result[1]);
}
}
class Solution {
public int[] twoSum(int[] nums, int target) {
int head = 0, tail = nums.length-1;
int temp;
//先对数组排序,但要另一个数组记录之前的位置
int[] order = new int[nums.length];
for(int i=0;i<nums.length;i++) {
order[i]=i;
}
for(int i = 0; i<tail-1; i++) {
for(int j = i+1; j<tail; j++) {
if(nums[i]>nums[j]) {
temp=nums[i];
nums[i]=nums[j];
nums[j]=temp;
temp=order[i];
order[i]=order[j];
order[j]=temp;
}
}
}
while(true) {
if(nums[head]+nums[tail]==target) {
if(order[head]> order[tail]) {
temp=order[head];
order[head]=order[tail];
order[tail]=temp;
}
int[] result = {order[head], order[tail]};
return result;
}
else if(nums[head]+nums[tail]<target) {
head++;
}
else if(nums[head]+nums[tail]>target) {
tail--;
}
}
}
}