2020-09-22刷题

  1. leetcode79-单词搜索
    题型:回溯、递归
    难度:中等
    题目:给定一个二维网格和一个单词,找出该单词是否存在于网格中。
    单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
    代码:
class Solution {
//遍历每个点,把每个点分别当成word的起始字符,如果满足,往后找
public:
    bool dfs(vector<vector<char>>& board, string word,int m,int n,int i,int j,int index){
        if(index == word.size()) return true;
        if(i<0 || j<0 || i>=m || j>=n) return false;
        //判断这个点符不符合
        if(word[index] != board[i][j]) return false;
        //如果符合,继续找这个节点上下左右节点是否满足,那么需要暂时把这个节点改掉
        char ch = board[i][j];
        board[i][j] = '0';
        bool b = (dfs(board,word,m,n,i+1,j,index+1) || 
            dfs(board,word,m,n,i-1,j,index+1) ||
            dfs(board,word,m,n,i,j+1,index+1) ||
            dfs(board,word,m,n,i,j-1,index+1)
        );
        board[i][j] = ch;
        return b;

    }
    bool exist(vector<vector<char>>& board, string word) {
        int m = board.size();
        if(m == 0) return false;
        int n = board[0].size();
        if(n == 0) return false;
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(dfs(board,word,m,n,i,j,0))
                    return true;
            }
        }
        return false;
    }
};
  1. LCP 06. 拿硬币
    难度:简单
    题目:桌上有 n 堆力扣币,每堆的数量保存在数组 coins 中。我们每次可以选择任意一堆,拿走其中的一枚或者两枚,求拿完所有力扣币的最少次数。
    代码:
class Solution {
public:
    int minCount(vector<int>& coins) {
        int m = coins.size();
        int res = 0;
        for(int i=0;i<m;i++)
        {
            while(coins[i] > 0)
            {
                coins[i] -= 2;
                res++;
            }
        }
        return res;
    }
};
  1. leetcode面试题02.08环路检测
    难度:中等
    题目:给定一个链表,如果它是有环链表,实现一个算法返回环路的开头节点。
    有环链表的定义:在链表中某个节点的next元素指向在它前面出现过的节点,则表明该链表存在环路。
    代码:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if(head==nullptr || head->next==nullptr) return nullptr;
        //判断是否有环
        ListNode *pFast = head;
        ListNode *pSlow = head;
        ListNode *pNode = nullptr;
        while(pSlow && pFast && pFast->next)
        {
            pSlow = pSlow->next;
            pFast = pFast->next->next;
            if(pSlow == pFast)
            {
                pNode = pSlow;
                break;
            }
        }
        if(!pNode) return nullptr;
        pFast = head;
        while(pFast != pSlow)
        {
            pFast = pFast->next;
            pSlow = pSlow->next;
        }
        return pFast;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值