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
                
  • 相关阅读:
    ubuntu 16.04 安装 python selenium
    DNS 小问题
    Ubuntu下安装setuptools
    ubuntu16.04LTS更换阿里源
    Ubuntu下安装 Phantomjs
    root和user切换
    Navicat破解安装教程
    urllib2
    MySQL划重点-查询-聚合-分组
    vi编辑器
  • 原文地址:https://www.cnblogs.com/whatyouthink/p/13205453.html
Copyright © 2011-2022 走看看