Leetcode 88 Merge Sorted Array

    xiaoxiao2025-07-13  5

    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.

    题目链接:https://leetcode.com/problems/merge-sorted-array/

    题目大意:将两个有序数组nums1和nums2合并到nums1中,保证nums1的空间足够

    题目分析:将nums1的值向后移n位,为了防止越界从最后一位向前移,然后两个指针比较并移动即可

    public class Solution { public void merge(int[] nums1, int m, int[] nums2, int n) { for(int i = m - 1; i >= 0; i--) { nums1[i + n] = nums1[i]; } int ptr1 = n, ptr2 = 0, ptr = 0; while(ptr1 < m + n && ptr2 < n) { if(nums1[ptr1] < nums2[ptr2]) { nums1[ptr ++] = nums1[ptr1 ++]; } else { nums1[ptr ++] = nums2[ptr2 ++]; } } while(ptr1 < m + n) { nums1[ptr ++] = nums1[ptr1 ++]; } while(ptr2 < n) { nums1[ptr ++] = nums2[ptr2 ++]; } } }

    转载请注明原文地址: https://ju.6miu.com/read-1300635.html
    最新回复(0)