zoukankan      html  css  js  c++  java
  • 【leetcode】1243. Array Transformation

    题目如下:

    Given an initial array arr, every day you produce a new array using the array of the previous day.

    On the i-th day, you do the following operations on the array of day i-1 to produce the array of day i:

    1. If an element is smaller than both its left neighbor and its right neighbor, then this element is incremented.
    2. If an element is bigger than both its left neighbor and its right neighbor, then this element is decremented.
    3. The first and last elements never change.

    After some days, the array does not change. Return that final array.

    Example 1:

    Input: arr = [6,2,3,4]
    Output: [6,3,3,4]
    Explanation: 
    On the first day, the array is changed from [6,2,3,4] to [6,3,3,4].
    No more operations can be done to this array.
    

    Example 2:

    Input: arr = [1,6,3,4,3,5]
    Output: [1,4,4,4,4,5]
    Explanation: 
    On the first day, the array is changed from [1,6,3,4,3,5] to [1,5,4,3,4,5].
    On the second day, the array is changed from [1,5,4,3,4,5] to [1,4,4,4,4,5].
    No more operations can be done to this array.

    Constraints:

    • 1 <= arr.length <= 100
    • 1 <= arr[i] <= 100

    解题思路:题目不难,注意每次变换前先备份arr,再根据备份的arr的值修改本身的arr。

    代码如下:

    class Solution(object):
        def transformArray(self, arr):
            """
            :type arr: List[int]
            :rtype: List[int]
            """
            while True:
                arr_bak = arr[::]
                for i in range(1,len(arr_bak)-1):
                    if arr_bak[i] > arr_bak[i-1] and arr_bak[i] > arr_bak[i+1]:
                        arr[i] -= 1
                    elif arr_bak[i] < arr_bak[i-1] and arr_bak[i] < arr_bak[i+1]:
                        arr[i] += 1
                if arr_bak == arr:
                    break
            return arr
            
  • 相关阅读:
    js模态框实现原理
    静态库、动态库------深入理解计算机系统
    链接器如何解析多重定义的全局符号(强弱符号)------深入理解计算机系统
    linux------深入理解linux内核
    libcurl坑
    《将博客搬至CSDN》
    openssl 编译
    vs2015+opencv3.3.1+ c++实现 静态背景下多运动目标提取,检测
    QT 相关书籍
    qml 知识积累
  • 原文地址:https://www.cnblogs.com/seyjs/p/11785282.html
Copyright © 2011-2022 走看看