Merge pull request #301 from 3ZadeSSG/master

Median of two sorted arrays No. 4
This commit is contained in:
Ashwek Swamy 2019-10-11 22:39:51 +05:30 committed by GitHub
commit 6221cbe7da
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 41 additions and 0 deletions

View File

@ -8,6 +8,7 @@ LeetCode
|---| ----- | -------- | ---------- |
|1|[Two Sum](https://https://leetcode.com/problems/two-sum/) | [C](./src/1.c)|Easy
|3|[Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters/) | [C](./src/3.c)|Medium|
|4|[Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/) | [C](./src/4.c)|Hard|
|20|[Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) | [C](./src/20.c)|Easy|
|24|[Swap Nodes in Pairs](https://leetcode.com/problems/swap-nodes-in-pairs/) | [C](./src/24.c)|Medium|
|26|[Remove Duplicates from Sorted Array](https://leetcode.com/problems/remove-duplicates-from-sorted-array/) | [C](./src/26.c)|Easy|

40
leetcode/src/4.c Normal file
View File

@ -0,0 +1,40 @@
double findMedianSortedArrays(int* nums1, int nums1Size, int* nums2, int nums2Size){
int index1=0;
int index2=0;
int v[nums1Size+nums2Size];
int v_index=0;
while(index1<nums1Size && index2<nums2Size){
if(nums1[index1]<=nums2[index2]){
v[v_index++]=nums1[index1++];
}
else{
v[v_index++]=nums2[index2++];
}
}
if(index1<nums1Size){
while(index1<nums1Size){
v[v_index++]=nums1[index1++];
}
}
if(index2<nums2Size){
while(index2<nums2Size){
v[v_index++]=nums2[index2++];
}
}
if(v_index==1){
return v[0];
}
if(v_index%2==0){
double n1,n2;
n1=v[v_index/2];
n2=v[(v_index/2)-1];
return (n1+n2)/2;
}
int new_index=(int)v_index/2;
int i=0;
return v[new_index];
}