Commit 9a73f265 by 李楚霏

week8

parent afc54e79
#include<string>
#include<vector>
#include<unordered_set>
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x): val(x), next(NULL) {}
};
class Solution {
public:
bool isPalindrome(ListNode* head) {
vector<ListNode*>res;
// 先存到一个vetor里
ListNode*ptr = head;
while(ptr != nullptr) {
// 反向存储链表的元素
cout<<"ptr.val"<<ptr->val<<endl;
res.emplace_back(ptr);
ptr = ptr->next;
}
int size = res.size()-1;
print(res);
// 从两边比较
for(int i =0, j = size; i < j ; i ++, j--) {
if (res[i]->val != res[j]->val){
return false;
}
}
return true;
}
void print (vector<ListNode*> & res) {
for(int i =0; i< res.size(); i++) {
cout<<res[i]->val<<",";
}
}
};
int main() {
Solution s;
auto t1 = new ListNode(1);
auto t2 = new ListNode(2);
auto t3 = new ListNode(2);
auto t4 = new ListNode(1);
t1->next= t2;
// t2->next = t3;
// t3->next= t4;
ListNode* head = t1;
s.isPalindrome(head);
return 0;
}
\ No newline at end of file
#include<string>
#include<string>
#include<vector>
#include<unordered_set>
#include<iostream>
using namespace std;
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
while (n != 0) {
cout<<"n1:"<<bitset<32>(n << 2) <<endl;
count++;
n = n & (n-1);
cout<<"n :"<<bitset<32>(n << 2)<<endl;
}
return count;
}
};
int main() {
Solution s;
int res;
res = s.hammingWeight(3);
cout<<res<<endl;
return 0;
}
\ No newline at end of file
class Solution {
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
n = (n << 16) | (n >> 16);
cout<<"1:"<<n<<endl;
n = ((n & 0xff00ff00)>> 8) | ((n & 0x00ff00ff) << 8);
cout<<"2:"<<n<<endl;
n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4);
cout<<"3:"<<n<<endl;
n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2);
cout<<"4:"<<n<<endl;
n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1);
cout<<"5:"<<n<<endl;
return n;
}
};
\ No newline at end of file
/**
/**
* @param {number[][]} M
* @return {number}
*/
var findCircleNum = function(M) {
if(M.length == 0) return;
let n = M.length;
let count =n;
let parent = new Array(n);
for(let i =0; i < n; i++) {
parent[i] = i;
}
const onion = (p, q) => {
let rootP = find(p);
let rootQ = find(q);
if (rootP === rootQ)
return;
parent[rootP] = rootQ;
count--;
}
const find = (p) => {
while(p !== parent[p]) {
parent[p] = parent[parent[p]];
p = parent[p];
}
return p;
}
for(let i =0; i < n; i++) {
for(let j =0; j < n; j++) {
if(M[i][j] === 1) {
onion(i, j);
}
}
}
return count;
};
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment