2021-06-01

博主刷题第六天,涉及多个算法题。包括实现x的平方根函数,用Rand7()实现Rand10(),判断括号字符串是否有效,以及判断链表是否为回文链表,这些都与信息技术领域的算法相关。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

刷题第六天
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;
	}
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值