c语言sscanf函数的用法是什么
248
2022-08-27
[leetcode] 88. Merge Sorted Array
Description
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
The number of elements initialized in nums1 and nums2 are m and n respectively. You may assume that nums1 has a size equal to m + n such that it has enough space to hold additional elements from nums2.
Example 1:
Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3Output: [1,2,2,3,5,6]
Example 2:
Input: nums1 = [1], m = 1, nums2 = [], n = 0Output: [1]
Constraints:
nums1.length == m + nnums2.length == n0 <= m, n <= 2001 <= m + n <= 200-109 <= nums1[i], nums2[i] <= 109
分析
题目的意思是:把两个有序的数组合并成一个数组,还要求把nums2合并到nums1,思路很直接。
nums1的最终的长度为m+n,然后nums1数组从后往前填数就行了
代码
class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ i=m-1 j=n-1 k=m+n-1 while(i>=0 and j>=0): if(nums1[i]>nums2[j]): nums1[k]=nums1[i] i-=1 else: nums1[k]=nums2[j] j-=1 k-=1 while(j>=0): nums1[k]=nums2[j] j-=1 k-=1
参考文献
合并两个有序数组[Leetcode]
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~