好搜网站提交入口网络营销网站平台有哪些
题目
解答
首先,使用的解题思路是:使用两个指针,分别指向数组的第一个0元素位置,以该元素位置+1为起始点寻找接下来第一个非0元素位置。二者确定后,对其进行交换。随后继续寻找下一个0元素位置。重复上述操作。
但第一次提交时出错,提示数组下标溢出。因此增加了对溢出情况的判断,考虑到两种指针,无论哪种指针溢出时,都代表交换已经完成,因此直接返回即可。
class Solution(object):def moveZeroes(self, nums):""":type nums: List[int]:rtype: None Do not return anything, modify nums in-place instead."""p_zero = 0p_one = 0l = len(nums)if l == 1:return numswhile p_one < l :while nums[p_zero] != 0:p_zero += 1if p_zero == l: # 增加判断return numsp_one = p_zero + 1if p_one == l: # 增加判断return numswhile nums[p_one] == 0:p_one += 1if p_one == l: # 增加判断return numsmed = nums[p_one]nums[p_one] = nums[p_zero]nums[p_zero] = medp_zero += 1return nums
看了一眼 怎么会如此耗时? 因为猪脑使用了很多while循环,无语,官方示例就很简单,思路一致。如下: