Created
October 17, 2018 18:34
-
-
Save hackallcode/a6700f02c5234ccc0e12b6793aabc97e to your computer and use it in GitHub Desktop.
This file contains 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> | |
#include <vector> | |
int FindTheSame(std::vector<int> array, size_t size, int elem) { | |
size_t left = 0; | |
size_t right = size - 1; | |
// Ищем промежуток | |
for (size_t i = 1; i < size; i *= 2) { | |
if (array[i] < elem) { | |
left = i; | |
} | |
if (array[i] >= elem) { | |
right = i; | |
break; | |
} | |
} | |
// Получаем самый левый элемент >= elem | |
while (right - left > 0) { | |
size_t mid = (left + right) / 2; | |
if (array[mid] >= elem) { | |
right = mid; | |
} else { | |
left = mid + 1; | |
} | |
} | |
// Найденный элемент минимален в массиве | |
if (left == 0) { | |
return 0; | |
} | |
else { | |
// У нас самый левый элемент, следовательно ближе может быть только предыдущий | |
return abs(array[left] - elem) < abs(array[left - 1] - elem) ? left : left - 1; | |
} | |
} | |
int main() { | |
std::vector<int> input{ 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 }; | |
std::cout << FindTheSame(input, input.size(), 22) << std::endl; | |
system("pause"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment