-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge Sorted Array
46 lines (46 loc) · 2.05 KB
/
Merge Sorted Array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
* Programmer : Dhruv Patel
* Problem Name : Merge Sorted Array
* Used In : Leetcode
* Used As : 88
* Problem =>
* Brute-Force 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.
*
* Thoughts => The two arrays are sorted hence the easiest solution would be to add numbers into the list and
* sort them. We then simply add to the nums1 array.This approach is the naive and brute-force.
* Also,it generates redundancy with O(M+N),where M is the total number of elements in nums1[] array
* and N is the total number of elements in nums2[] array.
*
*
*/
public class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
List<Integer> list = new ArrayList<>();
if(m>0){
for(int i : nums1){ // Iterating and adding elements to list
list.add(i);
m--; // Decrementing m to check Array out of Index
if(m<1){
break; // We break the loop if m is zero
}
}
}
if(n>0){
for(int j : nums2){ // Iterating and adding elements to list
list.add(j);
if(n<1){
break;
}
}
}
Collections.sort(list); // Sorting the list
int index = 0;
for(int i : list){
nums1[index] = i; // Adding numbers to the nums1 array
index++;
}
}
}