Created
April 15, 2020 07:24
-
-
Save misterpoloy/a936ad35fd86f23779336e265bff2d1f to your computer and use it in GitHub Desktop.
#CodeChallenge count how many times does N is contained in an array in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
int findFirstIndex(int* A, int n, int target, int position) { | |
int low, high; | |
low = 0; | |
high = n - 1; | |
int result = -1; | |
while (low <= high) { | |
int mid = low + (high - low) / 2; | |
if (target == A[mid]) { | |
if (position == 0) { | |
high = mid - 1; | |
} else { | |
low = mid + 1; | |
} | |
result = mid; | |
} | |
else if (target < A[mid]) { | |
high = mid - 1; | |
} else { | |
low = mid + 1; | |
} | |
} | |
return result; | |
} | |
int main() { | |
int arr[] = { 1, 2, 2, 2, 2, 2, 3, 4, 5 }; | |
int n = sizeof(arr) / sizeof(arr[0]); | |
int target = 2; | |
int leftIndex = findFirstIndex(arr, n, target, 0); | |
int rightIndex = findFirstIndex(arr, n, target, 1); | |
int times = rightIndex - leftIndex + 1; | |
std::cout << target << "appaers " << times << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment