移动零
283. 移动零 - 力扣(LeetCode)
看到这道题,是否第一个想法就是双指针,下面我们就来使用双指针来完成这道题.
图:
代码:
java:
// 移动 0 双指针public void moveZeroes(int[] nums) {for (int current = 0, dest = -1; current < nums.length; current++) {if (nums[current] != 0) {// 此时不等于 0 进行交换dest++;swapNumber(nums, current, dest);}}}public void swapNumber(int[] numbers, int left, int right) {int temp = numbers[left];numbers[left] = numbers[right];numbers[right] = temp;}
python:
class Solution(object):def moveZeroes(self, nums):current = 0dest = -1while len(nums):if nums[current] != 0:dest = dest + 1self.sawpNumbs(nums, current, dest)current = current + 1if current >= len(nums):breakdef sawpNumbs(self, nums, left, right):temp = nums[left]nums[left] = nums[right]nums[right] = temp
这里双指针,划分数组如果学过快排,应该会有映像.
复写零
仔细阅读题目,应该会有一个想法就是双指针, 一个进行遍历,一个进行复写,下面来看看思路.
图一:
图二:
java
public static void duplicateZeros(int[] arr) {int current = 0, dest = -1;while (current < arr.length) {if (arr[current] == 0) {dest += 2;} else {dest++;}if (dest >= arr.length - 1) {// 此时说明 current 到达了最后一个复写元素break;}current++;}if (dest == arr.length) {// 处理一下边界情况arr[arr.length - 1] = 0;current--;dest = dest - 2;}// 进行赋值操作while (current >= 0) {if (arr[current] != 0) {arr[dest--] = arr[current];} else {arr[dest--] = 0;arr[dest--] = 0;}current--;}}
python
class Solution(object):def duplicateZeros(self, arr):current = 0dest = -1while current < len(arr):if arr[current] == 0:dest += 2else:dest += 1if dest >= len(arr) - 1:breakcurrent += 1# 判断边界if dest == len(arr):arr[len(arr) - 1] = 0dest = dest - 2current = current - 1while current >= 0:if arr[current] != 0:arr[dest] = arr[current]dest = dest - 1else:arr[dest] = 0arr[dest - 1] = 0dest = dest - 2current = current - 1