如果对于所有的 0\le i < k 都有 2\cdot\textit{nums}[i]\le\textit{nums}[n-k+i],那么可以匹配 k 对。
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11
classSolution: defmaxNumOfMarkedIndices(self, nums: List[int]) -> int: nums.sort() left, right = 0, len(nums) // 2 + 1# 开区间 while left + 1 < right: k = (left + right) // 2 ifall(nums[i] * 2 <= nums[i - k] for i inrange(k)): left = k else: right = k return left * 2
[sol1-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution { publicintmaxNumOfMarkedIndices(int[] nums) { Arrays.sort(nums); intleft=0, right = nums.length / 2 + 1; // 开区间 while (left + 1 < right) { intmid= (left + right) >>> 1; if (check(nums, mid)) left = mid; else right = mid; } return left * 2; }
privatebooleancheck(int[] nums, int k) { for (inti=0; i < k; ++i) if (nums[i] * 2 > nums[nums.length - k + i]) returnfalse; returntrue; } }
classSolution: defmaxNumOfMarkedIndices(self, nums: List[int]) -> int: nums.sort() i = 0 for x in nums[(len(nums) + 1) // 2:]: if nums[i] * 2 <= x: i += 1 return i * 2
[sol2-Java]
1 2 3 4 5 6 7 8 9 10
classSolution { publicintmaxNumOfMarkedIndices(int[] nums) { Arrays.sort(nums); inti=0, n = nums.length; for (intj= (n + 1) / 2; j < n; ++j) if (nums[i] * 2 <= nums[j]) ++i; return i * 2; } }
[sol2-C++]
1 2 3 4 5 6 7 8 9 10 11
classSolution { public: intmaxNumOfMarkedIndices(vector<int> &nums){ sort(nums.begin(), nums.end()); int i = 0, n = nums.size(); for (int j = (n + 1) / 2; j < n; ++j) if (nums[i] * 2 <= nums[j]) ++i; return i * 2; } };
[sol2-Go]
1 2 3 4 5 6 7 8 9 10
funcmaxNumOfMarkedIndices(nums []int)int { sort.Ints(nums) i := 0 for _, x := range nums[(len(nums)+1)/2:] { if nums[i]*2 <= x { i++ } } return i * 2 }