https://leetcode-cn.com/problems/move-zeroes/

双指针

  1. //双指针
  2. // 两个原则
  3. // 1) i位置是0, i++
  4. // 2) i位置不是0. i位置跟to的下一个数交换, i++, to++
  5. public void moveZeroes(int[] nums) {
  6. int to = -1;
  7. for (int i = 0; i < nums.length; i++) {
  8. if (nums[i] != 0) {
  9. swap(i, ++to, nums);
  10. }
  11. }
  12. }
  13. private void swap(int i, int j, int[] nums) {
  14. int tmp = nums[i];
  15. nums[i] = nums[j];
  16. nums[j] = tmp;
  17. }