日記2022/0504

ALgorithm

Two Sum II - Input Array Is Sorted

C++

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) {
        int l = 0, r = numbers.size() - 1, sum;
        while (l < r) {
            sum = numbers[l] + numbers[r];
            if (sum == target) break;
            if (sum < target) ++l;
            else --r;
        }
        return vector<int>{l + 1, r + 1};
    }
};

在这里插入图片描述

Python

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        l = sum = 0
        r = len(numbers) -1
        while l < r:
            sum = numbers[l] + numbers[r]
            if sum == target:
                break
            if sum < target:
                l += 1
            else:
                r -= 1
        return [l+1,r+1]

在这里插入图片描述

88. Merge Sorted Array

C++

在这里插入图片描述

class Solution {
public:
    void merge(vector<int>& nums1, int m, vector<int>& nums2, int n) {
        int pos = m-- + n-- - 1;
        while (m >= 0 && n >= 0){
            nums1[pos--] = nums1[m] > nums2[n] ? nums1[m--]: nums2[n--];
        }
        while (n >= 0) {
            nums1[pos--] = nums2[n--];
        }
    }
};

Python

在这里插入图片描述

# Time: O(n + m) -> Total length of num1 list
# Space: O(1)
class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        length = m + n - 1      #Total length of num1 list
        m = m - 1
        n = n - 1
        for i in range(length, -1, -1):
            if n < 0:                                #Edge case when list2 is null or n -= 1 goes to -1
                break
            if nums1[m] > nums2[n] and m >= 0:       #Edge case when m -= 1 goes to -1
                nums1[i] = nums1[m]
                m -= 1
            else:
                nums1[i] = nums2[n]
                n -= 1
class Solution:
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """
        
        # remove zeros from nums1
        
        for value in range(n):
            if 0 in nums1:
                nums1.remove(0)
           
        # append nums2 items to the nums1 list
        for value in nums2:
            nums1.append(value)
        
        # sort in low to high order/non decreasing order
        nums1 = nums1.sort() 

142. Linked List Cycle II

C++

在这里插入图片描述

/**
 * 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) {
        ListNode *slow = head, *fast = head;
        do {
            if (!fast || !fast->next) return nullptr;
            fast = fast->next->next;
            slow = slow->next;
        } while (fast != slow);
        fast = head;
        while (fast != slow) {
            slow = slow->next;
            fast = fast->next;
        }
        return fast;
    }
};

Python

在这里插入图片描述

class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        slow = head
        fast = head
        if not head:
            return None
        if not head.next:
            return None
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
            
            if fast == slow:
                break
        if fast == slow:
            while fast != head:
                fast = fast.next
                head = head.next
            return head
        else:
            return None

Minimum Window Substring

C++

在这里插入图片描述

class Solution {
public:
    string minWindow(string s, string t) {
        vector<int> chars(128,0);
        vector<bool> flag(128, false);
        for (int i = 0; i < t.size(); ++i) {
            flag[t[i]] = true;
            ++chars[t[i]];
        }
        int cnt = 0, l = 0, min_l = 0, min_size = s.size() + 1;
        for (int r = 0; r < s.size(); ++r){
            if (flag[s[r]]){
                if (--chars[s[r]] >= 0){
                    ++cnt;
                }
                while (cnt == t.size()) {
                    if (r - l + 1 < min_size) {
                        min_l = l;
                        min_size = r - l + 1;
                    }
                    if (flag[s[l]] && ++chars[s[l]] > 0){
                        --cnt;
                    }
                    ++l;
                }
            }
        }
        return min_size > s.size()? "": s.substr(min_l, min_size);
    }
};

Python

在这里插入图片描述

class Solution:
    def minWindow(self, s: str, t: str) -> str:
        missing_chars = len(t) # how many characters we definitely need in the sliding window
        counter = {k:0 for k in t} # counter to keep track of count of chars of s in the current window
        orig_counter = Counter(t) # original counter of t to account for duplicate chars in t
        l = 0 # left pointer for sliding window
        out = [float('-inf'), float('inf')] # tuple to keep the shortest substring range in tow
        
        # keep incrementing r in a for loop
        for r in range(len(s)):
            # if the current char is in t
            # we increment its count in our sliding
            # window
            if s[r] in counter:
                # only decrement missing_chars IF the count of this
                # char is less than what we need i.e. count in t
                if counter[s[r]] < orig_counter[s[r]]: missing_chars -= 1
                counter[s[r]] += 1
            
            # If at any point we come across
            # missing chars as 0, it means we have
            # a valid substring, store it's range
            # in the out tuple
            while missing_chars <= 0:
                if (r-l) < (out[1]-out[0]): out = [l, r]
                
                # we're going to update our
                # counter if this char is present
                # in t
                if s[l] in counter:
                    counter[s[l]] -= 1
                    # same as before, only increment missing_chars
                    # IF the current count of char (after decrement)
                    # is still less than the original count i.e.
                    # the current sliding window now does not have 
                    # the required char count for this character and we're
                    # missing a character
                    if counter[s[l]] < orig_counter[s[l]]: missing_chars += 1
                
                # we are going to move our l
                # regardless until we are missing
                # a character again
                l += 1
                
        # return the string ranged bw the out tuple
        # if there is no string and out remains [-inf, inf]
        # return an empty string
        return s[out[0]:out[1]+1] if out[1]-out[0] < len(s) else ""
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值