classSolution { public: intpurchasePlans(vector<int>& nums, int target){ sort(nums.begin(), nums.end());
int ans = 0; int MOD = 1000000007; int pre = -1, pre_cnt = 0; for (int i = 0; i < nums.size(); ++i) { //cout << pre << ' ' << pre_cnt; if (pre >= 0 && nums[i] == nums[pre] && pre_cnt > 0) // 复用先前的方案 { ans = (ans + pre_cnt) % MOD; pre_cnt --; continue; }
int l = i + 1, r = nums.size() - 1, mid = (l + r + 1) >> 1; while(l < r) { if (nums[mid] + nums[i] > target) r = mid - 1; else l = mid; mid = (l + r + 1) >> 1; } if (nums[r] + nums[i] <= target) ans = (ans + (r - i)) % MOD; pre = i, pre_cnt = r - i - 1; }