332 周赛

66 阅读1分钟
  1. 找出数组的串联值
        int n = nums.size();
        long long ans = 0;
        for (int i = 0, j = n - 1; i <= j; i++, j--) {
            if (i < j) ans += stol(to_string(nums[i]) + to_string(nums[j]));
            else ans += nums[i];
        }
        return ans;
    }

使用stol与to_string节省时间

  1. 统计公平数对的数目 lower <= nums[i] + nums[j] <= upper ——>lower-nums[i]<=nums[j]<=upper-nums[i]
//////使用二分查找
long long countFairPairs(vector<int>& nums, int lower, int upper)
{
    long long res=0;
    int len=nums.size();
    sort(nums.begin(),num.end());
    
    for(int i=0;i<len-1;++i)
    {
        int l=lower-nums[i];
        int r=upper-nums[i];
        int index1=lower_bound(nums.begin(),nums.end(),l)-nums.begin();
        int index2=lower_bound(nums.begin(),nums.end(),r-nums.begin();
        
         //j的范围在[index1,index2),且j>i
            if(i>=index1 && i<index2) 
                res=index2-i-1;
            else if(i<index1)
                res+=index2-index1;
    }
    return res;
}