public void moveZeroes(int[] nums) {
int fastIndex = 0;
int showIndex;
for(showIndex = 0;fastIndex<=nums.length-1;fastIndex++){
if(nums[fastIndex] != 0){
//位运算交换数值,位运算比较快
nums[fastIndex] = nums[fastIndex] ^ nums[showIndex];
nums[showIndex] = nums[fastIndex] ^ nums[showIndex];
nums[fastIndex] = nums[fastIndex] ^ nums[showIndex];
/*也不使用中间变量
nums[fastIndex] = nums[showIndex] + nums[fastIndex];
nums[showIndex] = nums[fastIndex] - nums[showIndex];
nums[fastIndex] = nums[fastIndex] - nums[showIndex];
*/
showIndex++;
}
}
}
如果你说这题可以遍历找到有多少个零然后移动数组覆盖最后在数组后面添加零,我觉得这个不是这题的意思
采用快慢指针,代码简单可以自己看一下
但是这个解法只击败了60%,应该会有更好的
就这样