[Leetcode] 2460. Apply Operations to an Array (Easy)
概述
題目
https://leetcode.com/problems/apply-operations-to-an-array/
有點神奇的題目 XD,先從頭掃到尾,看是否有相鄰數字相同的組合,若有則前者 double、後者砍半,最後再左推非零數字
心得
本來誤解題目還想說是否由後往回做,後來確認只是模擬題,故操作完即可
Array
思路
先模擬後推數補零
程式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| class Solution(object): def applyOperations(self, nums): """ :type nums: List[int] :rtype: List[int] """ n = len(nums) for i in range(n-1): if nums[i+1] == nums[i]: nums[i] *= 2 nums[i+1] = 0 arr = [] for i in range(len(nums)): if nums[i] != 0: arr.append(nums[i]) while len(arr) < len(nums): arr.append(0) return arr
|
若是要 in-place 的話,以同向雙指針的方式做交換
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution(object): def applyOperations(self, nums): """ :type nums: List[int] :rtype: List[int] """ n = len(nums) for i in range(n-1): if nums[i+1] == nums[i]: nums[i] *= 2 nums[i+1] = 0 l = 0 for r in range(n): if nums[l] == 0 and nums[r] != 0: nums[l], nums[r] = nums[r], nums[l] elif nums[l] != 0: l += 1 return nums
|
Complexity
Time Complexity: O(n)
只在橫向 n 個數中操作,故 O(n)
Space Complexity: O(1)
基本上無使用到額外空間