【LeetCode】Merge Sorted Array
2014-03-07 10:15
302 查看
Merge Sorted Array
Total Accepted: 9111 Total Submissions: 28906 My Submissions
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
合并两个排序数组,典型题。这个需要从B合并到A,如果不声明新的空间的话,需要考虑到交换数据,操作起来反而麻烦些。不妨设置新的数组,将值赋给临时空间。这样就转为一般的合并题了。没什么难度,但是很需要基本功。
Java AC
Total Accepted: 9111 Total Submissions: 28906 My Submissions
Given two sorted integer arrays A and B, merge B into A as one sorted array.
Note:
You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively.
合并两个排序数组,典型题。这个需要从B合并到A,如果不声明新的空间的话,需要考虑到交换数据,操作起来反而麻烦些。不妨设置新的数组,将值赋给临时空间。这样就转为一般的合并题了。没什么难度,但是很需要基本功。
Java AC
public class Solution { public void merge(int A[], int m, int B[], int n) { int tempArr[] = new int[m]; System.arraycopy(A, 0, tempArr, 0, m); int k = 0; int i = 0; int j = 0; while (i < m && j < n) { if (tempArr[i] > B[j]) { A[k] = B[j]; j++; } else { A[k] = tempArr[i]; i++; } k++; } while (j < n) { A[k] = B[j]; k++; j++; } while (i < m) { A[k] = tempArr[i]; i++; k++; } } }
相关文章推荐
- [LeetCode]Merge Sorted Array
- [leetcode]_Merge Sorted Array
- leetcode 刷题之路 37 Merge Sorted Array
- LeetCode No.88 Merge Sorted Array
- [LeetCode]Merge Sorted Array
- leetcode 88: Merge Sorted Array
- leetcode[88]Merge Sorted Array
- leetcode 088 Merge Sorted Array
- LeetCode-Merge Sorted Array
- leetcode:Merge Sorted Array (合并排好序的数组)
- Merge Sorted Array - LeetCode
- leetcode -- Merge Sorted Array
- leetcode-Merge Sorted Array
- LeetCode之Merge Sorted Array
- Leetcode 88 Merge Sorted Array
- 79 leetcode - Merge Sorted Array
- leetcode-88-Merge Sorted Array
- LeetCode编程练习 - Merge Sorted Array学习心得
- [leetcode-88]Merge Sorted Array(C语言)
- 【leetcode】【88】Merge Sorted Array