二分查找-數組中負數與正數

/*  一個數組中中間部分都是0,前半部分全是負數,後半部分都是正數,要求時間複雜度儘量低的情況下,查找最後一個負數和第一個正數。
    題目中描述的數組,求解結果是與0比較的,可以看做是有序的,使用二分查找,時間複雜度可以達到log(n)
*/
#include <vector>
#include <iostream>

using namespace std;

// 二分查找
int BinSearch(const vector<int>& vect_nums, bool is_negative)
{
	int start = 0;
	int mid = 0;
	int end = vect_nums.size() - 1;

	while (start <= end)
	{
		mid = start + (end - start) / 2;
		if (vect_nums[mid] == 0)
		{
			if (is_negative) // 查找最後一個負數
			{
				end = mid - 1;
				if (vect_nums[end] < 0)
					return vect_nums[end];
			}
			else // 查找第一個正數
			{
				start = mid + 1;
				if (vect_nums[start] > 0)
					return vect_nums[start];
			}
		}
		else if (vect_nums[mid] > 0)
		{
			end = mid - 1;
		}
		else
		{
			start = mid + 1;
		}
	}
	
	return 0;
}

pair<int, int> BinSearchNegativePositive(const vector<int>& vect_nums)
{
	return make_pair(BinSearch(vect_nums, true), BinSearch(vect_nums, false));
}

int main()
{
	vector<int> vect_nums = { -1, -2, -8, -3, -10, 0, 0, 2, 3, 11};
	pair<int, int> pair_both_num = BinSearchNegativePositive(vect_nums);
	cout << "last negative: " << pair_both_num.first << ", first positive: " << pair_both_num.second;
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章