thảo luận Leetcode mỗi ngày

  • Người tạo chủ đề Người tạo chủ đề _Gia_Cat_Luong_
  • Ngày bắt đầu Ngày bắt đầu
Trạng thái
Không mở để trả lời thêm.
éo hiểu sao mấy bài hard e pick thấy acceptance rate cao mà e làm méo ra cả tuần nay rồi :ah:
ae làm thử, nay ko ra e đọc solution:
Ngon, đặt gạch mai cuối tuần trả lại fen 2 bài
zFNuZTA.gif

Mà mình cũng 2 attemps bài này rồi làm éo ra chắc khó thật rồi :((
via theNEXTvoz for iPhone
 
Python:
class Solution:
    def resultsArray(self, nums: List[int], k: int) -> List[int]:
        if k == 1:
            return nums
        
        n, result, count = len(nums), [-1 for _ in range(len(nums) - k + 1)], 1
        for i in range(1, n):
            if nums[i] == nums[i-1] + 1:
                count += 1
            else:
                count = 1
            if count >= k:
                result[i - k + 1] = nums[i]
        return result
 
Python:
class Solution:
    def resultsArray(self, nums: List[int], k: int) -> List[int]:
        ans = []
        count = 0
        for i in range(len(nums)):
            if i == 0 or nums[i - 1] + 1 == nums[i]:
                count += 1
            else:
                count = 1
            if i >= k - 1:
                if count >= k:
                    ans.append(nums[i])
                else:
                    ans.append(-1)
        return ans
 
Sửa lần cuối:
Java:
class Solution {
    public int[] resultsArray(int[] nums, int k) {
        int n = nums.length;
        int[] res = new int[n - k + 1];
        int cnt=1;
        for (int i = 1; i < k; i++) {
            if(nums[i-1]+1!=nums[i])cnt=1;
            else cnt++;
        }
        for (int i = k; i <= n; i++) {
            if(cnt==k)res[i-k]=nums[i-1];
            else res[i-k]=-1;
            if(i==n)break;
            if(nums[i-1]+1!=nums[i])cnt=1;
            else cnt=Math.min(cnt+1,k);
        }
        return res;
    }
}
 
ý tưởng là tìm sufix increase array và prfix increase array, join 2 thằng này lại tìm ra thằng mới rồi so sánh với 2 thằng kia
Python:
class Solution:
    def findLengthOfShortestSubarray(self, arr: List[int]) -> int:
        n = len(arr)
        left = 0
        while left < n - 1 and arr[left] <= arr[left + 1]:
            left += 1
        if left == n - 1:
            return 0
        right = n - 1
        while right > 0 and arr[right - 1] <= arr[right]:
            right -= 1
        result = min(n - left - 1, right) 
        i, j = 0, right
        while i <= left and j < n:
            if arr[i] <= arr[j]:
                result = min(result, j - i - 1)
                i += 1
            else:
                j += 1
        return result
 
Java:
class Solution {
    public int[] resultsArray(int[] nums, int k) {
        int n = nums.length;
        int[] res = new int[n - k + 1];
        Arrays.fill(res, -1);
        int low = 0;

        for (int high = 0; high < n; high++) {
            if (high > 0 && nums[high] != nums[high - 1] + 1) {
                low = high;
            }

            if (high - low + 1 == k) {
                res[low] = nums[high];
                low++;
            }
        }
        return res;
    }
}
 
Swift:
class Solution {
    func resultsArray(_ nums: [Int], _ k: Int) -> [Int] {
        guard nums.count > 1 else { return nums }
        guard k > 1 else { return nums }
        var result:[Int] = []
        var ascCount = 0
        for index in 1..<nums.count {
            let curNum = nums[index]
            if (nums[index-1] + 1) == curNum {
                ascCount += 1
            }
            if index >= k-1 {
                if index >= k && (nums[index-k] + 1) == nums[index-k+1] {
                    ascCount -= 1
                }
                result.append(ascCount == k-1 ? curNum : -1)
            }
        }
        return result
    }
}
 
C++:
func resultsArray(nums []int, k int) []int {
    n := len(nums)
    arr := make([]int, 0)

    for i := 0; i < n-k+1; i++ {

        flag := 0

        for j := i; j < i+k-1; j++ {
            if nums[j]+1 != nums[j+1] {
                flag = -1
                break
            }
        }

        if flag == -1 {
            arr = append(arr, -1)
        } else {
            arr = append(arr, nums[i+k-1])
        }

    }

    return arr
}
 
Em mới tập chơi leetcode
Ruby:
# @param {Integer[]} nums

# @param {Integer} k
# [USER=134385]@return[/USER] {Integer[]}
def results_array(nums, k)
    return [-1] if nums.length < k

    start_pos, end_pos = 0, k - 1
    result = []
    while end_pos < nums.length
        result << find_power_num(nums[start_pos..end_pos])
        end_pos += 1
        start_pos += 1
    end
    result
end

def find_power_num(sub_nums)
    sub_nums.each_with_index do |num, index|
        break if index == sub_nums.size - 1
        return -1 if num + 1 != sub_nums[index + 1]
    end
    sub_nums.last
end
 
C++:
vector<int> Solution::resultsArray(vector<int>& nums, int k) {
    if (k == 1)
        return nums;
    vector<int> ans;
    ans.reserve(nums.size());
    int left = 0;
    int consecutive  = 0;
    for (int right = 1; right < nums.size(); ++right) {
        if (nums[right] != 1 + nums[right - 1]) {
            consecutive = right;
        }
        if (right - left + 1 >= k) {
            if (consecutive <= left)
                ans.push_back(nums[right]);
            else
                ans.push_back(-1);
            left++;
        }
    }
    return ans;
}
 
bài này O(n) mà top 25% cùi, không biết rank theo tất cả hay chỉ cùng 1 ngôn ngữ các bác nhỉ

Java:
class Solution {
   
    fun resultsArray(nums: IntArray, k: Int): IntArray {
        if (k == 1) return nums
        val resultArr = IntArray(nums.size - k + 1) { -1 }
        var result = 1
        for (i in 1..nums.lastIndex) {
            if (nums[i] == nums[i - 1] + 1) {
                result++
                if (result >= k) resultArr[i + 1 - k] = nums[i]
            } else {
                result = 1
            }
        }

        return resultArr
    }
}
 
Python:
class Node:
    def __init__(self, start, end):
        self.start = start
        self.end = end
        self.mid = (start + end) >> 1
        self.min_val = float('inf')
        self.max_val = float('-inf')
        self.size = 0
        self.is_consecutive = False
        self.left = None
        self.right = None
        self.lazy = None


class SegmentTree:
    def __init__(self, n):
        self.root = self._build(0, n - 1)

    def _build(self, start, end):
        return Node(start, end)

    def _apply_lazy(self, node):
        if node.lazy is not None:
            node.min_val = node.max_val = node.lazy
            node.size = 1
            node.is_consecutive = True
            if node.start != node.end:
                if not node.left:
                    node.left = self._build(node.start, node.mid)
                if not node.right:
                    node.right = self._build(node.mid + 1, node.end)
                node.left.lazy = node.right.lazy = node.lazy
            node.lazy = None

    def update(self, pos, val, node=None):
        node = node or self.root
        self._apply_lazy(node)

        if pos < node.start or pos > node.end:
            return

        if node.start == node.end:
            node.min_val = node.max_val = val
            node.size = 1
            node.is_consecutive = True
            return

        if pos <= node.mid:
            if not node.left:
                node.left = self._build(node.start, node.mid)
            self.update(pos, val, node.left)
        else:
            if not node.right:
                node.right = self._build(node.mid + 1, node.end)
            self.update(pos, val, node.right)

        left = node.left
        right = node.right

        node.min_val = min(
            left.min_val if left else float('inf'),
            right.min_val if right else float('inf')
        )
        node.max_val = max(
            left.max_val if left else float('-inf'),
            right.max_val if right else float('-inf')
        )
        node.size = (
            (left.size if left else 0) +
            (right.size if right else 0)
        )

        node.is_consecutive = (
            (right.min_val - left.max_val == 1 if left and right else True) and
            (left.is_consecutive if left else True) and
            (right.is_consecutive if right else True) and
            node.size == (node.max_val - node.min_val + 1)
        )

    def query(self, start, end, node=None):
        node = node or self.root
        self._apply_lazy(node)

        if start > node.end or end < node.start:
            return True, float('inf'), float('-inf'), 0

        if start <= node.start and end >= node.end:
            return (
                node.is_consecutive,
                node.min_val,
                node.max_val,
                node.size,
            )

        left = (
            self.query(start, end, node.left)
            if node.left else (True, float('inf'), float('-inf'), 0)
        )
        right = (
            self.query(start, end, node.right)
            if node.right else (True, float('inf'), float('-inf'), 0)
        )

        left_cons, left_min, left_max, left_size = left
        right_cons, right_min, right_max, right_size = right

        is_consecutive = (
            left_cons and right_cons and
            (right_min - left_max == 1 if left_size and right_size else True) and
            (left_size + right_size == right_max - left_min + 1
                if left_size and right_size else True)
        )

        return (
            is_consecutive,
            min(left_min, right_min),
            max(left_max, right_max),
            left_size + right_size
        )

class Solution:
    def resultsArray(self, nums: List[int], k: int) -> List[int]:
        n = len(nums)
        tree = SegmentTree(n)

        for i, num in enumerate(nums):
            tree.update(i, num)

        result = []
        for i in range(n - k + 1):
            is_cons, _, max_val, size = tree.query(i, i + k - 1)
            result.append(max_val if is_cons and size == k else -1)

        return result
 
Python:
class Node:
    def __init__(self, start, end):
        self.start = start
        self.end = end
        self.mid = (start + end) >> 1
        self.min_val = float('inf')
        self.max_val = float('-inf')
        self.size = 0
        self.is_consecutive = False
        self.left = None
        self.right = None
        self.lazy = None


class SegmentTree:
    def __init__(self, n):
        self.root = self._build(0, n - 1)

    def _build(self, start, end):
        return Node(start, end)

    def _apply_lazy(self, node):
        if node.lazy is not None:
            node.min_val = node.max_val = node.lazy
            node.size = 1
            node.is_consecutive = True
            if node.start != node.end:
                if not node.left:
                    node.left = self._build(node.start, node.mid)
                if not node.right:
                    node.right = self._build(node.mid + 1, node.end)
                node.left.lazy = node.right.lazy = node.lazy
            node.lazy = None

    def update(self, pos, val, node=None):
        node = node or self.root
        self._apply_lazy(node)

        if pos < node.start or pos > node.end:
            return

        if node.start == node.end:
            node.min_val = node.max_val = val
            node.size = 1
            node.is_consecutive = True
            return

        if pos <= node.mid:
            if not node.left:
                node.left = self._build(node.start, node.mid)
            self.update(pos, val, node.left)
        else:
            if not node.right:
                node.right = self._build(node.mid + 1, node.end)
            self.update(pos, val, node.right)

        left = node.left
        right = node.right

        node.min_val = min(
            left.min_val if left else float('inf'),
            right.min_val if right else float('inf')
        )
        node.max_val = max(
            left.max_val if left else float('-inf'),
            right.max_val if right else float('-inf')
        )
        node.size = (
            (left.size if left else 0) +
            (right.size if right else 0)
        )

        node.is_consecutive = (
            (right.min_val - left.max_val == 1 if left and right else True) and
            (left.is_consecutive if left else True) and
            (right.is_consecutive if right else True) and
            node.size == (node.max_val - node.min_val + 1)
        )

    def query(self, start, end, node=None):
        node = node or self.root
        self._apply_lazy(node)

        if start > node.end or end < node.start:
            return True, float('inf'), float('-inf'), 0

        if start <= node.start and end >= node.end:
            return (
                node.is_consecutive,
                node.min_val,
                node.max_val,
                node.size,
            )

        left = (
            self.query(start, end, node.left)
            if node.left else (True, float('inf'), float('-inf'), 0)
        )
        right = (
            self.query(start, end, node.right)
            if node.right else (True, float('inf'), float('-inf'), 0)
        )

        left_cons, left_min, left_max, left_size = left
        right_cons, right_min, right_max, right_size = right

        is_consecutive = (
            left_cons and right_cons and
            (right_min - left_max == 1 if left_size and right_size else True) and
            (left_size + right_size == right_max - left_min + 1
                if left_size and right_size else True)
        )

        return (
            is_consecutive,
            min(left_min, right_min),
            max(left_max, right_max),
            left_size + right_size
        )

class Solution:
    def resultsArray(self, nums: List[int], k: int) -> List[int]:
        n = len(nums)
        tree = SegmentTree(n)

        for i, num in enumerate(nums):
            tree.update(i, num)

        result = []
        for i in range(n - k + 1):
            is_cons, _, max_val, size = tree.query(i, i + k - 1)
            result.append(max_val if is_cons and size == k else -1)

        return result
Magic
zFNuZTA.gif


via theNEXTvoz for iPhone
 
bài dễ lại ngoi lên :ah:
Java:
class Solution {
    public int[] resultsArray(int[] nums, int k) {
        int n = nums.length;
        int pre = 0;
        int windowSize = 0;
        int[] res= new  int[n-k+1];
        for(int i = 0;i<n;i++){
            if(i==0 || nums[i] == nums[i-1]+1)
                windowSize++;
            else
                windowSize = 1;
            if(i>=k-1)
                if (windowSize>=k)
                    res[i-k+1]=nums[i];
                else
                    res[i-k+1] = -1; 
        }
        return res;
    }
}
 
Trạng thái
Không mở để trả lời thêm.

Thống kê chủ đề

Ngày tạo
_Gia_Cat_Luong_,
Người trả lời cuối
Vipluckystar,
Trả lời
17.755
Lượt xem
1.215.683
Quay lại
Lên đầu trang