Skip to content

Instantly share code, notes, and snippets.

@aquawj
Last active November 12, 2017 07:37
Show Gist options
  • Save aquawj/a46c81d2dcc1d47e228d99e3d0aae76c to your computer and use it in GitHub Desktop.
Save aquawj/a46c81d2dcc1d47e228d99e3d0aae76c to your computer and use it in GitHub Desktop.
class Solution {
//1. write
//操作次数: nums.length
//适用:很多非零数。此法为写入次数最优!
public void moveZeroes(int[] nums) {
if(nums == null || nums.length == 0){
return;
}
int index = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] != 0 ){
nums[index++] = nums[i];
}
}
for(int i = index; i < nums.length; i++){
nums[i] = 0;
}
}
//2. swap
//操作次数: 2*非零个数
//适用:很多0
public void moveZeroes(int[] nums){
if(nums == null || nums.length == 0){
return;
}
int left = 0, right = 0;
while(right < nums.length){
if(nums[right] != 0){
int temp = nums[right];
nums[right] = nums[left];
nums[left] = temp;
left++;
}
right++;
}
}
//3. 不需要保持顺序:
public void moveZeroes(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int left = 0;
int right = nums.length - 1;
while (left < right) {
while (left < right&&nums[left] != 0) { //左侧都是该在左边的non-0
left++;
}
while (left < right&&nums[right] == 0) {//右侧都是该在右边的0
right--;
}
if (left < right) { //不该在左(右)的就交换
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
left++;
right--;
}
}
}
//4. 不需要保持顺序,只返回非0部分长度
//此时就不需交换(耗时),只赋值关心的部分即可
public int moveZeroes(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int left = 0;
int right = nums.length - 1;
while (left < right) {
while (left < right&&nums[left] != 0) { //左侧都是该在左边的non-0
left++;
}
while (left < right&&nums[right] == 0) {//右侧都是该在右边的0
right--;
}
if (left < right) {
nums[left++] = nums[right--]; //只把非0值写入左边即可,不用管后面
} //若是需要返回0的个数,上一步为 nums[right--] = nums[left++]; 最后返回right即可
}
return left;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment