88. Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.

Solution:Two Pointers

思路:其实和new一个result数组 然后对两个排好序的序列merge 的思路一样。只不过这里利用的是num1后面的多余空间。
Time Complexity: O(N) Space Complexity: O(1)

Solution Code:

class Solution {
    public void merge(int[] nums1, int m, int[] nums2, int n) {
        if(n == 0) return;
        
        int index1 = m - 1, index2 = n - 1;
        
        int k = m + n - 1;
        while(index1 >= 0 && index2 >= 0) {
            if(nums1[index1] > nums2[index2]) {
                nums1[k--] = nums1[index1--];
            }
            else {
                nums1[k--] = nums2[index2--];
            }
        }
        while(index2 >= 0) nums1[k--] = nums2[index2--];
        // while(index1 >= 0) nums1[k--] = nums1[index1--];
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Given two sorted integer arrays nums1 and nums2, merge nu...
    Jeanz阅读 222评论 0 0
  • Description Given two sorted integer arrays nums1 and num...
    Nancyberry阅读 117评论 0 0
  • 题目 Given two sorted integer arrays nums1 and nums2, merge...
    白菜炖豆腐阅读 229评论 0 0
  • 很多人来过又离开 我不确定你在不在其中 如果是你,应该会刮 37度的风,在这寒冬 如果是你,我会重回青春 哪怕被寒...
    CCHarbour阅读 470评论 2 3
  • 突然想写写昨天的事儿,昨天是闺蜜的生日。自然少不了聚会吃大餐,一起的不是闺蜜的朋友和同事,而是她的妈妈,哥哥,老公...
    随心一面镜阅读 265评论 0 0