classSolution { public: boolcheck(vector<int>& nums, int x, int m){ longlong sum = 0; int cnt = 1; for (int i = 0; i < nums.size(); i++) { if (sum + nums[i] > x) { cnt++; sum = nums[i]; } else { sum += nums[i]; } } return cnt <= m; }
intsplitArray(vector<int>& nums, int m){ longlong left = 0, right = 0; for (int i = 0; i < nums.size(); i++) { right += nums[i]; if (left < nums[i]) { left = nums[i]; } } while (left < right) { longlong mid = (left + right) >> 1; if (check(nums, mid, m)) { right = mid; } else { left = mid + 1; } } return left; } };
classSolution { public: vector<int> searchRange(vector<int> &nums, int target){ int n = nums.size(); if (n == 0) return {-1, -1}; int first = mylower(nums, target), last = mylower(nums, target+1)-1; if (first == nums.size() || nums[first] != target) return {-1, -1}; return {first, last}; } intmylower(vector<int> &nums, int target){ int left = 0, right = nums.size(), mid; while (left < right) { mid = left + (right - left) / 2; if (nums[mid] < target) left = mid + 1; else right = mid; } return left; } intmyupper(vector<int> &nums, int target){ int left = 0, right = nums.size(), mid; while (left < right) { mid = left + (right - left) / 2; if (nums[mid] <= target) left = mid + 1; else right = mid; } return left - 1; } };