本文主要是介绍【二分查找】Leetcode 点名,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目解析
LCR 173. 点名
算法讲解
1. 哈希表
class Solution {
public:int takeAttendance(vector<int>& nums) {map<int, int> Hash;for(auto n : nums) Hash[n]++;for(int i = 0; i <= nums[nums.size() - 1]; i++){if(Hash[i] == 0)return i;}return nums.size();}
};
2. 顺序遍历
class Solution {
public:int takeAttendance(vector<int>& nums) {int j = 0;for(int i = 0; i < nums.size() ; i++, j++){if(nums[i] != j)return j;}return j;}
};
3.位运算
class Solution {
public:int takeAttendance(vector<int>& nums) {int ret = 0;for(int i = 0; i < nums.size(); i++){ret ^= (nums[i] ^ (i+1));}return ret;}
};
二分法
class Solution {
public:int takeAttendance(vector<int>& nums) {//前半部分 nums[mid] == mid 后半部分 nums[mid] != midint left = 0, right = nums.size() - 1;while(left < right){int mid = left + (right - left) / 2;if(nums[mid] == mid)left = mid + 1;else right = mid;}if(nums[left] != left)return left;return left + 1;}
};
这篇关于【二分查找】Leetcode 点名的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!