leetcode 128. 最长连续序列 (hash,暴力)

题目大意:

给定一个未排序的整数数组,找出最长连续序列的长度。

要求算法的时间复杂度为 O(n)

解题思路:

我们每次枚举数字的第一个,然后往后数有多少个。可以证明每个数字只会被枚举一次。注意,中间用hash。

class Solution {
public:
    unordered_set<int> ms;
    int longestConsecutive(vector<int>& nums) {
        int ans = 0;
        for(auto it:nums)ms.insert(it);
        for(auto it:ms){
            if(!ms.count(it-1)){
                int no = it;
                int len = 1;
                while(ms.count(no))no++,len++;
                ans = max(ans,len-1);
            }
        }
        return ans;
    }
};

第二种方法是排序+递推

class Solution {
public:
    
    int longestConsecutive(vector<int>& nums) {
        if(nums.size() == 0)return 0;
        int ans = 1;
        
        sort(nums.begin(),nums.end());
        vector<int> dp(nums.size(),0);
        dp[0] = 1;
        int n = nums.size();
        for(int i =1;i<n;i++){
            if(nums[i] == nums[i-1]+1)dp[i] = dp[i-1]+1;
            else if(nums[i] == nums[i-1])dp[i] = dp[i-1];
            else dp[i] = 1;
            ans = max(ans,dp[i]);
        }
        return ans;
    }
};

 

### LeetCode Hot 100 Problems Python Solutions 以下是针对LeetCode热门100题中的部分经典题目提供Python实现方案: #### 两数之和 (Two Sum) 通过暴力解法可以遍历数组两次来找到目标值对应的索引位置[^1]。 ```python class Solution(object): def twoSum(self, nums, target): for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: return [i, j] return [] ``` 另一种更高效的解决方案是利用哈希表减少时间复杂度至O(n)[^4]: ```python class Solution(object): def twoSum(self, nums, target): hash_map = {} for index, value in enumerate(nums): complement = target - value if complement in hash_map: return [hash_map[complement], index] hash_map[value] = index return [] ``` --- #### 组合总和 (Combination Sum) 此问题可以通过回溯算法解决,递归构建满足条件的结果集[^2]。 ```python class Solution: def combinationSum(self, candidates, target): result = [] def backtrack(remain, comb, start): if remain == 0: result.append(list(comb)) return elif remain < 0: return for i in range(start, len(candidates)): comb.append(candidates[i]) backtrack(remain - candidates[i], comb, i) comb.pop() backtrack(target, [], 0) return result ``` --- #### 全排列 (Permutations) 对于全排列问题,同样采用回溯方法生成所有可能的排列组合。 ```python class Solution: def permute(self, nums): res = [] def backtrack(path, options): if not options: res.append(path[:]) return for i in range(len(options)): path.append(options[i]) backtrack(path, options[:i] + options[i+1:]) path.pop() backtrack([], nums) return res ``` --- #### 最长连续序列 (Longest Consecutive Sequence) 该问题的核心在于使用集合数据结构优化查找效率,从而降低整体的时间复杂度[^3]。 ```python class Solution: def longestConsecutive(self, nums): longest_streak = 0 num_set = set(nums) for num in num_set: if num - 1 not in num_set: current_num = num current_streak = 1 while current_num + 1 in num_set: current_num += 1 current_streak += 1 longest_streak = max(longest_streak, current_streak) return longest_streak ``` --- #### 字符串中所有字母异位词 (Find All Anagrams in a String) 滑动窗口配合字符计数器能够高效解决问题。 ```python from collections import defaultdict class Solution: def findAnagrams(self, s, p): need = defaultdict(int) window = defaultdict(int) valid = 0 for c in p: need[c] += 1 left, right = 0, 0 res = [] while right < len(s): c = s[right] right += 1 if c in need: window[c] += 1 if window[c] == need[c]: valid += 1 while right - left >= len(p): if valid == len(need): res.append(left) d = s[left] left += 1 if d in need: if window[d] == need[d]: valid -= 1 window[d] -= 1 return res ``` --- #### 两数相加 (Add Two Numbers) 链表操作的经典案例之一,需注意进位处理逻辑。 ```python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def addTwoNumbers(self, l1, l2): dummy_head = ListNode(0) curr = dummy_head carry = 0 while l1 or l2 or carry: x = l1.val if l1 else 0 y = l2.val if l2 else 0 total = x + y + carry carry = total // 10 curr.next = ListNode(total % 10) curr = curr.next if l1: l1 = l1.next if l2: l2 = l2.next return dummy_head.next ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值