力扣Hot100每日N题(19~24)

42. 环形链表 II

找规律

public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode fast = head, low = head;
        while(fast != null){
            low = low.next;
            if(fast.next == null) return null;
            fast = fast.next.next;
            if(fast == low){
                ListNode temp = head;
                while(temp != low){
                    temp = temp.next;
                    low = low.next;
                }
                return temp;
            }
        }
        return null;
    }
}

141. 环形链表

public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode fast = head, low = head;
        if(fast == null || fast.next == null) return false;
        while(fast != null){
            low = low.next;
            fast = fast.next;
            if(fast != null) fast = fast.next;
            if(fast == low) return true;
        }
        return false;
    }
}

139. 单词拆分

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        Set<String> wordDictSet = new HashSet<>(wordDict);
        boolean[] dp = new boolean[s.length() + 1];
        dp[0] = true;
        for(int i = 1; i <= s.length(); i++){
            for(int j = 0; j < i; j++){
                if(dp[j] && wordDictSet.contains(s.substring(j, i))){
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.length()];
    }
}

136. 只出现一次的数字

class Solution {
    public int singleNumber(int[] nums) {
        int result = 0;
        for (int i = 0; i < nums.length; i++) {
            result ^= nums[i];
        }
        return result;
    }
}

647. 回文子串

class Solution {
    public int countSubstrings(String s) {
        int ans = 0;
        for(int i = 0 ; i < s.length(); i++){
            ans += get(s, i, i) + get(s, i, i + 1);
        }
        return ans;
    }
    public int get(String s, int l, int r){
        int ans = 0;
        while(l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)){
            ans++;
            l--;
            r++;
        }
        return ans;
    }
}

128. 最长连续序列

class Solution {
    public int longestConsecutive(int[] nums) {
        Set<Integer> map = new HashSet<>();
        for(int num : nums) map.add(num);
        int ans = 0;
        for(int num : map){
            if(map.contains(num - 1)) continue;
            int len = 1, now = num;
            while(map.contains(now + 1)){
                len++;
                now++;
            }
            ans = Math.max(ans, len);
        }
        return ans;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值