leetcode第一题求助

Little BigUs 2021-04-26 11:14:02

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--;
}
}
}
}
...全文
221 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
Little BigUs 2021-04-27
  • 打赏
  • 举报
回复
引用 1 楼 qybao的回复:
你这个都排序了,元素的下标还是原来的下标吗? 直接两层循环,数组两两元素相加判断和就可以了,不用整这么复杂。
确实,但我还是想知道我这为什么数组越界了,我用了一个order数组记录原来的下标
qybao 2021-04-27
  • 打赏
  • 举报
回复
你这个都排序了,元素的下标还是原来的下标吗? 直接两层循环,数组两两元素相加判断和就可以了,不用整这么复杂。

58,451

社区成员

发帖
与我相关
我的任务
社区描述
Java Eclipse
社区管理员
  • Eclipse
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧