c# leetcode 1389. 按既定順序創建目標數組 (數組)

難度簡單4收藏分享切換爲英文關注反饋

給你兩個整數數組 nums 和 index。你需要按照以下規則創建目標數組:

  • 目標數組 target 最初爲空。
  • 按從左到右的順序依次讀取 nums[i] 和 index[i],在 target 數組中的下標 index[i] 處插入值 nums[i] 。
  • 重複上一步,直到在 nums 和 index 中都沒有要讀取的元素。

請你返回目標數組。

題目保證數字插入位置總是存在。

 

示例 1:

輸入:nums = [0,1,2,3,4], index = [0,1,2,2,1]
輸出:[0,4,1,3,2]
解釋:
nums       index     target
0            0        [0]
1            1        [0,1]
2            2        [0,1,2]
3            2        [0,1,3,2]
4            1        [0,4,1,3,2]

示例 2:

輸入:nums = [1,2,3,4,0], index = [0,1,2,3,0]
輸出:[0,1,2,3,4]
解釋:
nums       index     target
1            0        [1]
2            1        [1,2]
3            2        [1,2,3]
4            3        [1,2,3,4]
0            0        [0,1,2,3,4]

示例 3:

輸入:nums = [1], index = [0]
輸出:[1]

 

提示:

  • 1 <= nums.length, index.length <= 100
  • nums.length == index.length
  • 0 <= nums[i] <= 100
  • 0 <= index[i] <= i

插入:

        public static int[] CreateTargetArray(int[] nums, int[] index)
        { 
            List<int> target = new List<int>(nums.Length);
            for (int i = 0; i < nums.Length; i++)
            {
                target.Insert(index[i], nums[i]);
            }
            return target.Take(nums.Length).ToArray(); 
        } 

調用:

        static void Main(string[] args)
        {
            int[] nums = new int[] { 0, 1, 2, 3, 4 };
            int[] index = new int[] { 0, 1, 2, 2, 1 };
            CreateTargetArray(nums, index);
        }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章