mirror of
https://github.com/huihut/interview.git
synced 2026-03-13 10:02:55 +08:00
66. Plus One 、 88. Merge Sorted Array
This commit is contained in:
@@ -10,6 +10,7 @@ public:
|
||||
return (findKth(nums1, 0, nums2, 0, len / 2) + findKth(nums1, 0, nums2, 0, len / 2 + 1)) / 2;
|
||||
}
|
||||
|
||||
// find kth number of two sorted array
|
||||
double findKth(vector<int>& nums1, int i1, vector<int>& nums2, int i2, int k) {
|
||||
if (i1 >= nums1.size()) {
|
||||
return nums2[i2 + k - 1];
|
||||
|
||||
15
Problems/LeetcodeProblems/66-plus-one.h
Normal file
15
Problems/LeetcodeProblems/66-plus-one.h
Normal file
@@ -0,0 +1,15 @@
|
||||
class Solution {
|
||||
public:
|
||||
vector<int> plusOne(vector<int>& digits) {
|
||||
int carry = 1;
|
||||
for(int i = digits.size() - 1; i >= 0; --i) {
|
||||
int add = digits[i] + carry;
|
||||
digits[i] = add % 10;
|
||||
carry = add / 10;
|
||||
}
|
||||
if(carry > 0) {
|
||||
digits.insert(digits.begin(), carry);
|
||||
}
|
||||
return digits;
|
||||
}
|
||||
};
|
||||
20
Problems/LeetcodeProblems/88-merge-sorted-array.h
Normal file
20
Problems/LeetcodeProblems/88-merge-sorted-array.h
Normal file
@@ -0,0 +1,20 @@
|
||||
class Solution {
|
||||
public:
|
||||
void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
|
||||
int i1 = m - 1, i2 = n - 1;
|
||||
for(int i = m + n - 1; i >= 0; i--) {
|
||||
if(i1 >= 0 && i2 < 0)
|
||||
break;
|
||||
if(i1 < 0 && i2 >= 0) {
|
||||
nums1[i] = nums2[i2--];
|
||||
}
|
||||
if(i1 >= 0 && i2 >= 0) {
|
||||
if(nums1[i1] > nums2[i2]) {
|
||||
nums1[i] = nums1[i1--];
|
||||
} else {
|
||||
nums1[i] = nums2[i2--];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user