标签:main pow prime ret get node 窗口 pull not
class Solution { public: int rob(vector<int>& nums) { const int n = nums.size(); if (n == 0) return 0; if (n == 1) return nums[0]; if (n == 2) return max(nums[0], nums[1]); vector<int> f(n, 0); f[0] = nums[0]; f[1] = max(nums[0], nums[1]); for (int i = 2; i < n; ++i) f[i] = max(f[i-2] + nums[i], f[i-1]); return f[n-1]; } };
class Solution { public: bool isHappy(int n) { unordered_map<int,int> tmp; while(n != 1) { if(tmp[n] == 0) tmp[n]++; else return false; int sum = 0; while(n != 0) { sum += pow(n % 10,2); n = n / 10; } n = sum; } return true; } }; /////////////////////////// class Solution { public: int next(int n) { int sum = 0; while(n != 0) { sum += pow(n % 10,2); n = n / 10; } return sum; } public: bool isHappy(int n) { int slow = next(n); int fast = next(next(n)); while(slow != fast) { slow = next(slow); fast = next(next(fast)); } return fast == 1 ; } };
class Solution { public: int countPrimes(int n) { //Sieve of Erantothoses vector<bool> check(n+1,true); //Because 0 and 1 are not primes check[0]=false; check[1]=false; //OPtimization 2: Do only till rootn since all numbers after that are handled //The remaining values are already true for(int i=2;i*i<=n;i++) { //If already visited if(check[i]==false) continue; //Optimation 1 : 3*2 is already handled by 2*3. Toh directly start from 9 int j=i*i; while(j<=n) { check[j]=false; j = j+i; } } int count=0; //Checking all the numbers which are prime (less than n) for(int i=1;i<n;i++) if(check[i]) count++; return count; } };
固定窗口滑动
class Solution { public: bool containsNearbyDuplicate(vector<int>& nums, int k) { unordered_set<int> s; if (k <= 0) return false; if (k >= nums.size()) k = nums.size() - 1; for (int i = 0; i < nums.size(); i++) { if (i > k) s.erase(nums[i - k - 1]); if (s.find(nums[i]) != s.end()) return true; s.insert(nums[i]); } return false; } };
class Solution { public: bool isPowerOfTwo(int n) { if(n<=0) return false; return !(n&(n-1)); } };
class Solution { public: bool isPalindrome(ListNode* head) { if(head==NULL||head->next==NULL) return true; ListNode* slow=head; ListNode* fast=head; while(fast->next!=NULL&&fast->next->next!=NULL){ slow=slow->next; fast=fast->next->next; } slow->next=reverseList(slow->next); slow=slow->next; while(slow!=NULL){ if(head->val!=slow->val) return false; head=head->next; slow=slow->next; } return true; } ListNode* reverseList(ListNode* head) { ListNode* pre=NULL; ListNode* next=NULL; while(head!=NULL){ next=head->next; head->next=pre; pre=head; head=next; } return pre; } };
标签:main pow prime ret get node 窗口 pull not
原文地址:https://www.cnblogs.com/hotsnow/p/9739635.html