Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

88. 合并两个有序数组 #9

Open
yankewei opened this issue Mar 3, 2020 · 0 comments
Open

88. 合并两个有序数组 #9

yankewei opened this issue Mar 3, 2020 · 0 comments
Labels
双指针 题目包含双指针解法 数组 题目类型为数组 简单 题目难度为简单

Comments

@yankewei
Copy link
Owner

yankewei commented Mar 3, 2020

给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组。

说明:

初始化 nums1 和 nums2 的元素数量分别为 m 和 n。
你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。

示例:

输入:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3

输出: [1,2,2,3,5,6]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-sorted-array

首先题目给出了条件,两个有序数组nums1nums2,最后要合并到nums1中,并且nums1中肯定有足够的空间,也就是满足len(nums1) >= m + n,结果也是一个有序数组
既然知道给定的长度并且是有序的,那么我们可以直接从尾部遍历元素,把较大的值添加了nums1中,要注意的是,mn的值并不是相等的,所以我们在执行遍历的时候需要注意mn的值,把剩余的元素追加到nums1

func merge(nums1 []int, m int, nums2 []int, n int)  {
    index := m + n -1
    m--
    n--
    for m >= 0 || n >= 0 {
        if m >= 0 && n >= 0 {
            if nums1[m] >= nums2[n] {
                nums1[index] = nums1[m]
                m--
            } else {
                nums1[index] = nums2[n]
		n--
	    }
	} else if m >= 0 {
	    nums1[index] = nums1[m]
	    m--
	} else if n >= 0 {
	    nums1[index] = nums2[n]
	    n--
	}
	index--
    }
}
@yankewei yankewei added 简单 题目难度为简单 数组 题目类型为数组 双指针 题目包含双指针解法 labels Mar 3, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
双指针 题目包含双指针解法 数组 题目类型为数组 简单 题目难度为简单
Projects
None yet
Development

No branches or pull requests

1 participant