力扣题目训练(2)

2024年1月26日力扣题目训练

2024年1月26日第二天编程训练,今天主要是进行一些题训练,包括简单题3道、中等题2道和困难题1道,前天忘记发了。

263. 丑数

链接: 丑数
难度: 简单
题目:
题目描述
思路:
按照定义,只用是否有除了2、3、5以外的质因数。

268. 丢失的数字

链接: 丢失的数字
难度: 简单
题目:
题目描述
思路:
利用哈希表,看哪个不在就是缺失的数字。

283. 移动零

链接: 移动零
难度: 简单
题目:
题目描述
思路:
双指针对数组进行操作。

86. 分隔链表

链接: 分隔链表
难度: 中等
题目:
题目描述

运行示例:
运行示例
思路:
利用双指针,一个指向小于x的值,一个指向大于x的值。
代码:

class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        ListNode* newhead = new ListNode(0);
        ListNode* bighead = new ListNode(0);
        ListNode* p = newhead;
        ListNode* q = bighead;
        while(head != NULL){
            if(head->val < x){
                p->next = head;
                p = p->next;
            }else{
                q->next = head;
                q = q->next;
            }
            head = head->next;
        }
        p->next = bighead->next;
        q->next = NULL;
        return newhead->next;
    }
};

89. 格雷编码

链接: 格雷编码
难度: 中等
题目:
题目描述
运行示例:
运行示例

思路:
我们可以发现不管n为几,当前n的格雷码中的前一半始终为n - 1的全部,所以这时我们可以忽略n在格雷码中的影响,只用在之前的基础上加上0与1即可。
代码:

class Solution {
public:
    vector<int> grayCode(int n) {
        vector<int> res;
        res.push_back(0);
        int begin = 1;
        for(int i = 0; i < n; i++){
            for(int j = res.size()-1; j >= 0; j--){
                res.push_back(begin+res[j]);
            }
            begin <<= 1;
        }
        return res;
    }
};

37. 解数独

链接: 解数独
难度: 困难
题目:
题目描述
运行示例:
运行示例
思路:
回溯法判断填入的数字是否合法。

代码:

class Solution {
public:
    bool isValid(vector<vector<char>>&board,int row, int col, char ch){
        for(int i = 0; i < 9; i++){
            if(board[row][i] == ch) return false;
            if(board[i][col] == ch) return false;
            if(board[(row/3)*3+i/3][(col/3)*3+i%3] == ch) return false;
        }
        return true;
    }
    bool backtrack(vector<vector<char>>&board,int row,int col){
        if(col == 9) return backtrack(board,row+1,0);
        if(row == 9) return true;
        for(int i = row; i < 9; i++){
            for(int j = col; j < 9; j++){
                if(board[i][j] != '.'){
                    return backtrack(board,i,j+1);
                }
                for(char ch = '1'; ch <= '9'; ch++){
                    if(!isValid(board,i,j,ch)) continue;
                    board[i][j] = ch;
                    if(backtrack(board,i,j+1)) return true;
                    board[i][j] = '.';
                }
                return false;
            }
        }
        return false;
    }
    void solveSudoku(vector<vector<char>>& board) {
        backtrack(board,0,0);
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值