1521. 找到最接近目标值的函数值
参考https://space.bilibili.com/3203291/零神的题解
class Solution { public: int closestToTarget(vector<int>& arr, int target) { int ans = abs(arr[0] - target); vector<int> valid = {arr[0]}; for (int num: arr) { vector<int> validNew = {num}; ans = min(ans, abs(num - target)); for (int prev: valid) { validNew.push_back(prev & num); ans = min(ans, abs((prev & num) - target)); } validNew.erase(unique(validNew.begin(), validNew.end()), validNew.end()); valid = validNew; } return ans; } };
class Solution { public int closestToTarget(int[] arr, int target) { HashSet<Integer> cur = new HashSet<>(); int min = Integer.MAX_VALUE; for(int i : arr){ HashSet<Integer> cur2 = new HashSet<>(); cur2.add(i); min = Math.min(min,Math.abs(target-i)); for(int j : cur){ int val = j&i; cur2.add(val); min = Math.min(min,Math.abs(target-val)); } cur = cur2; } return min; } }