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
                
  • 相关阅读:
    sock编程
    Exceptional c++
    sort
    实现UDP高效接收/响应
    Iterator invalidation(迭代器失效)
    php 判断一个点是否在一个多边形区域内
    PHP 如何在txt里查找包含某个字符串的那一行?
    php 实现栈与队列
    微信支付 接口
    文章添加,删除,修改,分页列表
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13205453.html
Copyright © 2011-2022 走看看