移动零
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
说明:
- 必须在原数组上操作,不能拷贝额外的数组。
- 尽量减少操作次数。
在不要求排序的时候,可以用下面的代码
class Solution {
public void moveZeroes(int[] nums) {
if ( nums.length == 0 ) {
return;
}
int left = 0;
int right = nums.length -1;
while(left <= right){
while(nums[right] == 0 && right >0){
right--;
}
if(right <=left ){
break;
}
if(nums[left] == 0){
nums[left] = nums[right];
nums[right] = 0;
left++;
right--;
} else {
left++;
}
}
}
}
要求排序
class Solution {
public void moveZeroes(int[] nums) {
if ( nums.length == 0 || nums.length == 1) {
return;
}
//left 用来找零 right用来找非零
int left = 0;
int right = left + 1;
while(right < nums.length){
while ((left < nums.length) && nums[left] != 0 ){
left++;
}
while (right < nums.length && (left >= right || nums[right] == 0) ){
right++;
}
if(right >= nums.length){
return;
}
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right++;
}
}
}
网上其他更简单的方案
int i = 0,j = 0;
for(i = 0 ; i < numsSize; i++)
{
if(nums[i] != 0)
{
nums[j++] = nums[i];
}
}
while(j < numsSize)
{
nums[j++] = 0;
}
两数之和 II - 输入有序数组
给定一个已按照非递减顺序排列的整数数组 numbers ,请你从数组中找出两个数满足相加之和等于目标数 target 。
函数应该以长度为 2 的整数数组的形式返回这两个数的下标值。numbers 的下标 从 1 开始计数 ,所以答案数组应当满足 1 <= answer[0] < answer[1] <= numbers.length 。
你可以假设每个输入 只对应唯一的答案 ,而且你不可以重复使用相同的元素。
示例:
输入:numbers = [2,7,11,15], target = 9
输出:[1,2]
解释:2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。
输入: numbers = [2,3,4], target = 6
输出: [1,3]
输入: numbers = [-1,0], target = -1
输出: [1,2]
class Solution {
public int[] twoSum(int[] numbers, int target) {
if(numbers.length == 0){
return new int[]{-1};
}
if(numbers.length == 1){
if(numbers[0] == target){
return new int[]{1};
} else {
return new int[]{-1};
}
}
int left = 0;
int right = numbers.length - 1;
while(left < right){
int sum = numbers[left] + numbers[right];
if(sum > target){
right--;
} else if(sum < target){
left++;
} else {
return new int[]{++left, ++right};
}
}
return new int[]{-1};
}
}