zoukankan      html  css  js  c++  java
  • 1389. Create Target Array in the Given Order

    Given two arrays of integers nums and index. Your task is to create target array under the following rules:

    • Initially target array is empty.
    • From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array.
    • Repeat the previous step until there are no elements to read in nums and index.

    Return the target array.

    It is guaranteed that the insertion operations will be valid.

    方法就是按照他给的index模拟一下就行。

    看discussion有人说求index的逆序数,index加上对应位置的逆序数值就是最终的index值。我想了这个做法实际上是不对的,举一个反例

    nums = [4,2,4,3,2] index = [0,0,1,3,1] index的逆序数=[1,0,1,1,0] 最终的index=[1,0,2,4,1],很明显是不对的。

    class Solution(object):
        def createTargetArray(self, nums, index):
            """
            :type nums: List[int]
            :type index: List[int]
            :rtype: List[int]
            """
            ans = []
            for i in range(len(index)):
                if index[i] >= len(ans):
                    ans.append(nums[i])
                else:
                    ans = ans[:index[i]] + [nums[i]] + ans[index[i]:]
            return ans
                
  • 相关阅读:
    86. 分隔链表
    85. 最大矩形
    84. 柱状图中最大的矩形
    82. 删除排序链表中的重复元素 II
    80. 删除排序数组中的重复项 II
    77. 组合
    java-xml
    java-反射
    springboot解决跨域问题(CorsConfig )
    解决oracle锁表
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13205453.html
Copyright © 2011-2022 走看看