1. Move Zeros
给一个数组,将数组里的0全部移到数组最后。
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
LeetCode里很多题目要求”do this in-place”,通俗的理解就是算法输出结果覆盖算法的输入,这样做可以节省内存。
我的代码实现如下:
class Solution(object):
def moveZeroes(self, nums):
for i in range(nums.count(0)):
nums.remove(0)
nums.extend([0]*count0)
思路比较简单,由于remove(x)函数每次只能删除第一个遇到的x,因此这里首先将所有0移除,然后在最后用extend()的方法将0添加到nums最后。
2. Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
我最开始的思路是遍历nums中所有的元素,然后count每个元素出现的次数,提交代码的时候被拒绝了,结论是:”Runtime Limited Error”超时了。确实,这样的实现方法时间复杂度为 O(