leetcode(c++)(二分查找)
#include <iostream> #include <numeric> #include <algorithm> #include <vector> using namespace std; double findMediaSorted(const vector<int>&n1,const vector<int>& n2) { int m = n1.size(),n = n2.size(); if(m > n)return findMediaSorted(n2,n1); int left = 0, right = m; while(left <= right){ int x = left + (right - left ) / 2; int y = (m + n + 1) / 2 - x; int xLeft = (x == 0) ? INT_MIN : n1[x-1]; int xRight = (x == m) ? INT_MAX : n1[x]; int yLeft = (y == 0) ? INT_MIN : n2[y-1]; int yRight = (y == n) ? INT_MAX : n2[y]; if(xLeft <= yRight && yLeft <= xRight) { if((m + n) % 2 == 0)return (double)(max(xLeft,yLeft), min(xRight,yRight)) / 2.0; else return (double)max(xLeft,yLeft); } else if(xRight > yLeft) right = x - 1; else left = x + 1; } return -1; } bool valid(const vector<int>& nums,int m, int sum) { int curSum = 0, cnt = 1; for(auto num : nums) { curSum += num; if(curSum > sum) { curSum = num; ++cnt; if(cnt > m)return false; } } return true; } int binary(const vector<int>& nums,int m, int low,int high) { while(low <= high) { int mid = low + (high - low) / 2; if(valid(nums,m,mid))high = mid - 1; else low = mid + 1; } return low; } int splitArray(const vector<int>& nums, int m) { int sum = accumulate(nums.begin(),nums.end(),0); int maxVal = *(max_element(nums.begin(),nums.end())); return binary(nums,m,maxVal,sum); } bool check(int x, vector<int>& position,int m) { int pre = position[0],cnt = 1; for(int i = 1; i < position.size(); ++i) { if(position[i] - pre >= x) { pre = position[i]; ++cnt; } } return cnt >= m; } int maxDistance(vector<int>& position,int m) { sort(position.begin(),position.end()); int left = 1, right = position.back() - position[0],res = -1; while(left <= right) { int mid = left + (right - left ) / 2; if(check(mid,position,m)) { res = mid; left = mid + 1; } else { right = mid - 1; } } return res; } int main() { //LeetCode4 vector<int>nums1{1,3}; vector<int>nums2{2}; cout << findMediaSorted(nums1,nums2) << endl; //LeetCode410 vector<int> nums{7,2,5,10,8}; int m = 2; cout << splitArray(nums,m) << endl; //LeetCode1552 nums = {1,2,3,4,7}; m = 3; cout << maxDistance(nums,m) << endl; return 0; }