贴一下灵神的题解里面的解释~
就是一种优化策略,logtrick
class Solution {
public:int minimumDifference(vector<int>& nums, int k) {int res = 0x3f3f3f3f;int n = nums.size();for(int i=0;i<n;i++){res = min(res,abs(nums[i]-k));for(int j = i-1;j>=0&&(nums[j]|nums[i])!=nums[j];--j){nums[j] |= nums[i];res = min(res,abs(nums[j]-k));}}return res;};
};
同理换成AND的话就是看当前元素是不是前面的超集就好了
class Solution {
public:int closestToTarget(vector<int>& arr, int target) {int n = arr.size();int res = 0x3f3f3f3f;for(int i=0;i<n;i++){res = min(res,abs(target-arr[i]));for(int j=i-1;j>=0&&(arr[j]&arr[i])!=arr[j];--j){arr[j]&=arr[i];res = min(res,abs(target-arr[j]));}}return res;}
};