Python gives you an array nums with indexes starting from 0. The array size is n and consists of non-negative integers.

  1. Perform operations on arrays

You are given an array nums with indexes starting from 0. The array size is n and consists of non-negative integers.

You need to perform n - 1 steps on the array, where the i-th step (counting from 0) requires > executing the following instructions on the i-th element in nums:

If nums[i] == nums[i + 1], then the value of nums[i] becomes 2 times the original value, and the value of nums[i + 1] becomes 0. Otherwise, skip this step.
After all operations are performed, move all 0's to the end of the array.

For example, the array [1,0,2,0,0,1] becomes [1,2,1,0,0,0] after moving all 0's to the end.
Returns an array of results.

Note that operations should be performed sequentially and not all at once.

Example 1:

Input: nums = [1,2,2,1,1,0]
Output: [1,4,2,0,0,0]
Explanation: Perform the following operations:

  • i = 0: nums[0] and nums[1] are not equal, skip this step.
  • i = 1: nums[1] and nums[2] are equal, the value of nums[1] becomes twice the original value, and the value of >nums[2] becomes 0. The array becomes [1,4,0,1,1,0].
  • i = 2: nums[2] and nums[3] are not equal, so skip this step.
  • i = 3: nums[3] and nums[4] are equal, the value of nums[3] becomes twice the original value, and the value of >nums[4] becomes 0. The array becomes [1,4,0,2,0,0].
  • i = 4: nums[4] and nums[5] are equal, the value of nums[4] becomes twice the original value, and the value of >nums[5] becomes 0. The array becomes [1,4,0,2,0,0].
    After all operations are performed, all 0s are moved to the end of the array to obtain the result array [1,4,2,0,0,0].

Example 2:

Input: nums = [0,1]
Output: [1,0]
Explanation: Nothing can be done, just move 0 to the end.

hint:

2 <= nums.length <= 2000
0 <= nums[i] <= 1000

Screenshot of execution results

Insert image description here

My Python Answers

class Solution(object):
    def applyOperations(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        # 遍历列表执行指定操作
        nums = [1,2,2,1,1,0]
        for i in range(len(nums)-1):
            if nums[i] != nums[i+1]:
                continue
            nums[i] = nums[i]*2
            nums[i+1] = 0
        # 去掉元素为0的
        a = [i for i in nums if i]
        # 元素不为0的加上元素0列表并返回          
        return a+[0 for i in range(len(nums) - len(a))]

Guess you like

Origin blog.csdn.net/gixome/article/details/131044143