5.17领扣--Arrays.copyOf()方法

 ??

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

?????

class Solution {
public int[] twoSum(int[] nums, int target) {
//创建一个存放2个索引的数组,数组长度为2.
int[] r1 = new int[2];
//复制一个一摸一样的数组r2.
int[] r2 = Arrays.copyOf(nums, nums.length);
//排序参数中的数组,是从小到大进行排序.
Arrays.sort(nums);
//定义一个整数变量,等于数组的长度减1
int j = nums.length - 1;

//if判断数组长度减一减一后对应的索引对应的值“+”数组长度减一对应的索引对应的值如果
//---说大于等于target的话可以进行下一步的操作
if ((nums[j - 1] + nums[j]) >= target) {
//if判断数组长度减一减一后对应的索引对应的值“+”数组长度减一对应的索引对应的值
//---说等于target的话可以进行下一步操作
if ((nums[j - 1] + nums[j]) == target) {//倒数第二+倒数第三
//定义两个boolean类型add---add2
Boolean add = false;
Boolean add2 = false;
//for循环遍历没有排序的(原封复制参数数组)r2
for (int q = 0; q <= r2.length - 1; q++) {
//if判断数组长度减一减一后对应的索引对应的值(排序过的参数数组)对应的值如果“等 //---于”r2数组的索引对应的值
//r2中的第一个索引
if (nums[j - 1] == r2[q] && !add) {//!!!!!!!!!!注意这个感叹号
r1[0] = q;
add = true;
continue;
}
//r2中的第二个索引
if (nums[j] == r2[q] && !add2) {
r1[1] = q;
add2 = true;
continue;
}
if (add && add2) {
break;
}
}


} else {
//遍历循环j是数组长度减一后的值0123=4即变化成123=3长度
for (int i = 0; i <= j; ) {//j=4-1=3长度

if ((nums[i] + nums[j]) == target) {//排序后的数组
//变成true跳出用
Boolean add = false;
Boolean add2 = false;
for (int q = 0; q <= r2.length - 1; q++) {//遍历没有排序的数组
if (nums[i] == r2[q] && !add) {
r1[0] = q;
add = true;
continue;
}
if (nums[j] == r2[q] && !add2) {
r1[1] = q;
add2 = true;
continue;
}
if (add2 && add) {
break;
}

}
break;
}

if ((nums[i] + nums[j]) < target) {//判断排序的数组【i前j后】---slse下的for //---内部
i++;//****注意这里i++即i+1因为for循环中没有i++****
//因为排序且小于目标所以i(前)需要++,得到i索引对应的大的的值
continue;
}
;
if ((nums[i] + nums[j]) > target) {
j--;
continue;
}

扫描二维码关注公众号,回复: 6252753 查看本文章

}
}
}

return r1;
}
}

1.Arrays.copyOf()方法理解:

   用于复制指定的数组内容以达到扩容的目的,该方法对不同的基本数据类型都有对应的重载方法。

2.Arrays.sort()的几种用法    https://blog.csdn.net/qq_41763225/article/details/82890122

  Java中的Arrays类中有一个sort()方法,该方法是Arrays类的静态方法,在需要对数组进行排序时,非常好用。

  2.1 Arrays.sort(int[]a):对一个数组所有元素进行排序,并且是从小到大排序。int[] a = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5}; Arrays.sort(a);0123456789

  2.2 Arrays.sort(int[]a,int fromlIndex,int toIndex):这种形式是对数组a的下标从fromIndex到toIndex-1的元素排序,注意下标toIndex的元素不参与排序。int[] a = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5}; Arrays.sort(a, 0, 3);7 8 9

3.continue表示跳出当次循环

猜你喜欢

转载自www.cnblogs.com/wym591273/p/10883464.html