#905 Sort Array By Parity
Given an integer array
nums
, move all the even integers at the beginning of the array followed by all the odd integers.Return any array that satisfies this condition.
解题思路:
沿用上次搜到#283 move zeroes Zitao Wang的思路,用两指针解,偶数就互换,奇数左指针就不右移。
class Solution:
def sortArrayByParity(self, nums: List[int]) -> List[int]:
left = 0
for right in range(len(nums)):
if nums[right] % 2 == 0:
nums[left], nums[right] = nums[right], nums[left]
left += 1
return nums
runtime:
绝了。这思路果然强大。果然Discussion Forum里高手多,是个宝藏要多挖掘学习。
#1051 Height Checker
A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array
expected
whereexpected[i]
is the expected height of theith
student in line.You are given an integer array
heights
representing the current order that the students are standing in. Eachheights[i]
is the height of theith
student in line (0-indexed).Return the number of indices where
heights[i] != expected[i]
.
解题思路:
用sorted()生成新的list,然后挨个对比,计数不等的元素。
class Solution:
def heightChecker(self, heights: List[int]) -> int:
expected = sorted(heights)
count = 0
for idx in range(len(heights)):
if expected[idx] != heights[idx]:
count += 1
return count
runtime:
明天再看看forum里有没有更好的解法。今天先这样吧。奈特。
---------------------------------------------------5月21日分割线-------------------------------------------------------
forum里cenkay写了个one-liner,可以统计heights出现的频率。拿 [1,1,4,2,1,3] 为例,统计频率之后,就是[0,3,1,1,1] 这里的idx就是height。本来想重写一遍,但发现不知道怎么表达元素也idx之间的对应关系。参考了一下leihao1313的代码(太妙了):
class Solution:
def heightChecker(self, heights: List[int]) -> int:
c = Counter(heights)
res = i = 0
for h in heights:
while not c[i]:
i += 1
res += i != h
c[i] -= 1
return res
通过Counter(heights)得到[0,3,1,1,1]。然后res相当于计数的,i是idx。
对于heights里的每个元素,如果某个高度的频次是0,那么idx自动进一位。当idx不是当前元素时,res加1。
(BTW,res += i != h 这一行一开始完全看不懂在干嘛,先再pycharm里试:
但结果出来是8,不是3。完全不理解为什么可以连续两个operator在一行。不知道哪个表达式应该先处理。后来,再试res += 1,就对了。才明白,是看i是否等于h。等的话,默认res加0;不等,res才加1。)
然后Counter(heigts)对应idx的数字减1,在for循环里再看下一个元素等不等与idx。
自己再重写一遍看看:
class Solution:
def heightChecker(self, heights: List[int]) -> int:
c = Counter(heights)
counter = idx = 0
for i in heights:
while c[idx] == 0:
idx += 1
counter += idx != i
c[idx] -= 1
return counter
runtime:
这里很不理解。为什么这种方法的time complexity是O(N),但居然表现不如sorted过的O(NlogN)? 不科学啊……