刷题第六天
1、x的平方根
实现 int sqrt(int x) 函数。
class Solution {
public:
int mySqrt(int x) {
int l = 0, r = x, res = 0;
while(l <= r){
int mid = (l + r) / 2;
if((long long)mid * mid <= x){
res = mid;
l = mid + 1;
}
else
r = mid - 1;
}
return res;
}
};
2、用Rand7()实现Rand10()
已有方法 rand7 可生成 1 到 7 范围内的均匀随机整数,试写一个方法 rand10 生成 1 到 10 范围内的均匀随机整数。
class Solution {
public:
int rand10() {
int row, col, idx;
do {
row = rand7();
col = rand7();
idx = col + (row - 1) * 7;
} while (idx > 40);
return 1 + (idx - 1) % 10;
}
};
3、有效的括号
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串 s ,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
class Solution{
public:
bool isValid(string s) {
int len = s.size();
if(len % 2 == 1) return false;
unordered_map<char, int> map{{'(' , 1},{'[' , 2},{'{' , 3},{')' , 4},{']' , 5},{'}' , 6}};
stack<char> stack;
for(auto c : s){
int flag = map[c];
if(flag >= 1 && flag <= 3)
stack.push(c);
else if(!stack.empty() && flag - 3 == map[stack.top()])
stack.pop();
else
return false;
}
if(!stack.empty()) return false;
return true;
}
};
4、回文链表
请判断一个链表是否为回文链表。
class Solution{
public:
ListNode* getfirsthalf(ListNode* head){
ListNode* fast = head;
ListNode* slow = head;
while(fast->next && fast->next->next){
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
ListNode* reverseList(ListNode* head){
ListNode* cur = head;
ListNode* pre = nullptr;
while(cur){
ListNode* tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
return pre;
}
bool isPalindrome(ListNode* head) {
if(head == nullptr) return false;
ListNode* f1 = getfirsthalf(head);
ListNode* f2 = reverseList(f1->next);
ListNode* l1 = head;
ListNode* l2 = f2;
bool result = true;
while(result && l2 != nullptr){
if(l1->val != l2->val) return false;
l1 = l1->next;
l2 = l2->next;
}
f1->next = reverseList(f2);
return result;
}
};