diff options
Diffstat (limited to 'top-interview-questions/easy/sorting_and_searching')
| -rw-r--r-- | top-interview-questions/easy/sorting_and_searching/01_merge_sorted_array.cc | 24 | ||||
| -rw-r--r-- | top-interview-questions/easy/sorting_and_searching/02_first_bad_version.cc | 21 |
2 files changed, 45 insertions, 0 deletions
diff --git a/top-interview-questions/easy/sorting_and_searching/01_merge_sorted_array.cc b/top-interview-questions/easy/sorting_and_searching/01_merge_sorted_array.cc new file mode 100644 index 0000000..9abb974 --- /dev/null +++ b/top-interview-questions/easy/sorting_and_searching/01_merge_sorted_array.cc | |||
| @@ -0,0 +1,24 @@ | |||
| 1 | class Solution { | ||
| 2 | public: | ||
| 3 | void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) { | ||
| 4 | int i = m-1; | ||
| 5 | int j = n-1; | ||
| 6 | int k = n+m-1; | ||
| 7 | |||
| 8 | while ((i >= 0) && (j >= 0)) { | ||
| 9 | if (nums1[i] >= nums2[j]) { | ||
| 10 | nums1[k--] = nums1[i--]; | ||
| 11 | } else { | ||
| 12 | nums1[k--] = nums2[j--]; | ||
| 13 | } | ||
| 14 | } | ||
| 15 | |||
| 16 | while (i >= 0) { | ||
| 17 | nums1[k--] = nums1[i--]; | ||
| 18 | } | ||
| 19 | |||
| 20 | while (j >= 0) { | ||
| 21 | nums1[k--] = nums2[j--]; | ||
| 22 | } | ||
| 23 | } | ||
| 24 | }; | ||
diff --git a/top-interview-questions/easy/sorting_and_searching/02_first_bad_version.cc b/top-interview-questions/easy/sorting_and_searching/02_first_bad_version.cc new file mode 100644 index 0000000..15e2504 --- /dev/null +++ b/top-interview-questions/easy/sorting_and_searching/02_first_bad_version.cc | |||
| @@ -0,0 +1,21 @@ | |||
| 1 | // The API isBadVersion is defined for you. | ||
| 2 | // bool isBadVersion(int version); | ||
| 3 | |||
| 4 | class Solution { | ||
| 5 | public: | ||
| 6 | int FirstBad(int left, int right) { | ||
| 7 | if (left == right) { | ||
| 8 | return left; | ||
| 9 | } | ||
| 10 | const int mid = left + (right - left) / 2; | ||
| 11 | if (isBadVersion(mid)) { | ||
| 12 | return FirstBad(left, mid); | ||
| 13 | } else { | ||
| 14 | return FirstBad(mid+1, right); | ||
| 15 | } | ||
| 16 | } | ||
| 17 | |||
| 18 | int firstBadVersion(int n) { | ||
| 19 | return FirstBad(1, n); | ||
| 20 | } | ||
| 21 | }; | ||
