有序数组的平方
class Solution {
public int[] sortedSquares(int[] nums) {
//数组最右边下标的位置
int right = nums.length - 1;
//数组最左边下标的位置
int left = 0;
//新建一个与原数组长度等同的新数组
int[] result = new int[nums.length];
//创建一个在循环中唯一固定下标
int index = result.length - 1;
//当左边没有超过右边时进行以下操作
while (left <= right) {
//如果左边平方大于右边平方则将左边放在最高位
if (nums[left] * nums[left] > nums[right] * nums[right]) {
//index-- 代表先用后减
result[index--] = nums[left] * nums[left];
++left;
} else {
result[index--] = nums[right] * nums[right];
--right;
}
}
return result;
}
}
旋转数组
class Solution {
public void rotate(int[] nums, int k) {
int[] replication = new int[nums.length];
int len = nums.length;
// 对数组进行复制
for (int i = 0; i < nums.length; i++) {
replication[i] = nums[i];
}
// 如果超过了数组长度,则进行取余数
k = k % len;
// 将倒数 k个元素赋值给原来数组的前 k 位
for (int i = 0; i < k; i++) {
nums[k-i-1] = replication[len-i-1];
}
for (int j = 0; j < len-k; j++) {
nums[k+j] = replication[j];
}
}
}
都是抄别人的,这玩意不看别人的思路,上不了手