class Solution {
public:
int findDuplicate(vector<int>& nums) {
int n = nums.size() - 1;
int l = 1, r = n;
while (l < r){
int mid = l + r >> 1;
int cnt = 0;
for (auto x : nums)
if (x >= l && x <= mid)
cnt++;
if (cnt > mid - l + 1) r = mid;
else l = mid + 1;
}
return r;
}
};
上述代码中
for (auto x : nums)
作用就是迭代容器中所有的元素,每一个元素的临时名字就是x,等同于下边代码
for (vector<int>::iterator iter = nums.begin(); iter != nums.end(); iter++)