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

  • Người tạo chủ đề Người tạo chủ đề Vipluckystar
  • Ngày bắt đầu Ngày bắt đầu
Java:
class Solution {
    public int[] pivotArray(int[] nums, int pivot) {
        int n = nums.length;      
        int[] ans = new int[n];
        int j = 0;
        for (int i = 0; i < n; i++) {
            if (nums[i] < pivot) ans[j++] = nums[i];
        }
        for (int i = 0; i < n; i++) {
            if (nums[i] == pivot) ans[j++] = nums[i];
        }
        for (int i = 0; i < n; i++) {
            if (nums[i] > pivot) ans[j++] = nums[i];
        }
        return ans;
    }
}
 
JavaScript:
var pivotArray = function(nums, pivot) {
    const left = []
    const right = []
    const equal = []

    for(let i =0; i<nums.length; i++) {
        if(nums[i]< pivot){
            left.push(nums[i])
        } else if(nums[i]> pivot) {
            right.push(nums[i])
        } else {
            equal.push(nums[i])
        }
    }

    return left.concat(equal,right)
};
 
Java:
public int[] pivotArray(int[] nums, int pivot) {
    int p = 0;
    int len = nums.length;
    int[] result = new int[len];
    // Handle nums[i] < pivot
    for (int num : nums) {
        if (num < pivot) {
            result[p++] = num;
        }
    }
    // Handle nums[i] == pivot
    for (int num : nums) {
        if (num == pivot) {
            result[p++] = num;
        }
    }
    // Handle nums[i] > pivot
    for (int num : nums) {
        if (num > pivot) {
            result[p++] = num;
        }
    }
    return result;
}
 
C-like:
func pivotArray(a []int, p int) []int {
    var store [3][]int
    for _, v := range a {
        if v < p {
            store[0] = append(store[0], v)
        } else if v == p {
            store[1] = append(store[1], v)
        } else {
            store[2] = append(store[2], v)
        }
    }
    a = a[:0]
    for i, _ := range store {
        for j, _ := range store[i] {
            a = append(a, store[i][j])
        }
    }
    return a;
}
 
Mã:
class Solution:
    def pivotArray(self, nums: List[int], pivot: int) -> List[int]:
        less = []
        greater = []
        equal = []

        for num in nums:
            if num < pivot: less.append(num)
            elif num > pivot: greater.append(num)
            else: equal.append(num)
        
        return less + equal + greater
 
Java:
class Solution {
    public int[] pivotArray(int[] nums, int pivot) {
        int n =nums.length;
        int p_index =0;
        Queue<Integer> less = new LinkedList<>();
        Queue<Integer> greater = new LinkedList<>();
        int equal_cnt=0;
        for(int num:nums){
            if(num<pivot){less.add(num);}
            else if(num>pivot) {greater.add(num);}
            else equal_cnt++;
        }
        int index =0;
        while(!less.isEmpty()){
            nums[index++] = less.poll();
        }
        while(equal_cnt>0){
            nums[index++] = pivot;
            equal_cnt--;
        }
        while(!greater.isEmpty()){
            nums[index++] = greater.poll();
        }
        return nums;
    }
}
 
mấy bài hôm nay toàn merge sort quick sort nhỉ
hard sort is coming :burn_joss_stick:
Python:
class Solution:
    def pivotArray(self, nums: List[int], pivot: int) -> List[int]:
        less = []
        greater = []
        cntEqual = 0
        for num in nums :
            if num > pivot :
                greater.append(num)
            elif num < pivot :
                less.append(num)
            else :
                cntEqual += 1
        equal = [pivot] * cntEqual
        
        answer = less + equal + greater
        return answer
 
Java:
class Solution {
    public int[] pivotArray(int[] nums, int pivot) {
        int[] result = new int[nums.length];
        Queue<Integer> left = new LinkedList<>();
        Queue<Integer> right = new LinkedList<>();
        int equalPivot = 0;

        for(int i = 0 ;i < nums.length;i++){
            if(nums[i] == pivot){
                equalPivot++;
                continue;
            }
            if(nums[i] < pivot){
                left.add(nums[i]);
                continue;
            }

            if(nums[i] > pivot){
                right.add(nums[i]);
                continue;
            }
        }
        int k = 0;
        while(!left.isEmpty()){
            result[k] = left.poll();
            k++;
        }
        while(equalPivot-- > 0){
            result[k] = pivot;
            k++;
        }

        while(!right.isEmpty()){
            result[k] = right.poll();
            k++;
        }

        return result;
    }
}
 
JavaScript:
var pivotArray = function (nums, pivot) {
    const smaller = [];
    const bigger = [];
    const equal = [];
    for (const num of nums) {
        if (num < pivot) smaller.push(num);
        else if (num > pivot) bigger.push(num);
        else equal.push(num);
    }
    return smaller.concat(equal, bigger);
};
 
med giả cầy, nothing special
JCFtpJo.png

Python:
class Solution:
    def pivotArray(self, nums: List[int], pivot: int) -> List[int]:
        smaller = []
        equal = []
        greater = []
        for n in nums:
            if n<pivot:
                smaller.append(n)
            elif n== pivot:
                equal.append(n)
            else:
                greater.append(n)
        equal.extend(greater)
        smaller.extend(equal)
        return smaller
 
Python:
class Solution:
    def pivotArray(self, nums: List[int], pivot: int) -> List[int]:
        smaller = []
        bigger = []
        is_pivot = []
        for num in nums:
            if num > pivot:
                bigger.append(num)
            elif num < pivot:
                smaller.append(num)
            else:
                is_pivot.append(num)
        result = [*smaller, *is_pivot, *bigger]
        return result
 
C-like:
use std::cmp::Ordering;

impl Solution {
    pub fn pivot_array(nums: Vec<i32>, pivot: i32) -> Vec<i32> {
        let n = nums.len();
        let mut solution = vec![0; n];

        let (ltc, eqc, _) =
            nums.iter().copied().
                fold((0, 0, 0), |(ltc, eqc, gtc), num| {
                    match num.cmp(&pivot) {
                        Ordering::Equal => (ltc, eqc + 1, gtc),
                        Ordering::Greater => (ltc, eqc, gtc + 1),
                        Ordering::Less => (ltc + 1, eqc, gtc)
                    }
                });

        let (mut i, mut j) = (0, ltc + eqc);

        for k in 0..n {
            match nums[k].cmp(&pivot) {
                Ordering::Equal => (),
                Ordering::Less => {
                    solution[i] = nums[k];
                    i += 1;
                },
                Ordering::Greater => {
                    solution[j] = nums[k];
                    j += 1;
                }
            }
        }

        j = i + eqc;
        while i < j {
            solution[i] = pivot;
            i += 1;
        }

        solution
    }
}
 
Swift:
class Solution {
    func pivotArray(_ nums: [Int], _ pivot: Int) -> [Int] {
        var less:[Int] = []
        var pv:[Int] = []
        var great:[Int] = []
        for num in nums {
            if num < pivot {
                less.append(num)
            } else if num > pivot {
                great.append(num)
            } else {
                pv.append(num)
            }
        }
        return less + pv + great
    }
}
 
C#:
public class Solution {
    public int[] PivotArray(int[] nums, int pivot) {
        var start = new List<int>();
        var mid = new List<int>();
        var end = new List<int>();
        foreach (var num in nums)
        {
            if (num < pivot)
                start.Add(num);
            if (num == pivot)
                mid.Add(num);
            if (num > pivot)
                end.Add(num);
        }
        start.AddRange(mid);
        start.AddRange(end);
        return start.ToArray();
    }
}
 
Còn dễ hơn mấy bài easy hôm trước

C#:
public class Solution {
    public int[] PivotArray(int[] nums, int pivot) {
        var leftPivot = new List<int>();
        var rightPivot = new List<int>();
        var listPivot = new List<int>();

        for (var i = 0; i < nums.Length; i++)
        {
            if (nums[i] < pivot)
            {
                leftPivot.Add(nums[i]);
            }
            else if (nums[i] > pivot) {
                rightPivot.Add(nums[i]);
            }
            else {
                listPivot.Add(pivot);
            }
        }

        var result = leftPivot.Concat(listPivot).Concat(rightPivot);

        return result.ToArray();
    }
}
 
JavaScript:
/**
 * @param {number[]} nums
 * @param {number} pivot
 * @return {number[]}
 */
var pivotArray = function (nums, pivot) {
  const less = [];
  const greater = [];
  const equal = [];
  for (let num of nums) {
    if (num < pivot) less.push(num);
    else if (num > pivot) greater.push(num);
    else equal.push(pivot);
  }
  return less.concat(equal, greater);
};
 
JavaScript:
var checkPowersOfThree = function(n) {
    while(n>0) {
        if(n%3 > 1) return false
        n = n/3 | 0
    }

    return true
};
 
Python:
class Solution:
    def checkPowersOfThree(self, n: int) -> bool:
        i = 16
        while i >= 0:
            if (n >= pow(3, i)): n -= pow(3, i)
            i -= 1
        return n == 0
 
Chưa đọc hint thì bài này là bài thuộc dạng chọn or bỏ qua, ta có thể sử dụng backtracking để tính tổng tất cả các tổ hợp từ 3^0 -> 3^k < n.
Sau khi đọc hint rồi thì mới biết thêm tính chất của số tam phân. Thấy anh em post nhiều solution cách này rồi nên mình chỉ post code backtracking vậy.


Python:
class Solution:
    def checkPowersOfThree(self, n: int) -> bool:
        k = 1
        powerOfThree = []
        i = 0
        while k <= n:
            k = 3**i
            powerOfThree.append(k)
            i += 1
        def backtracking(s, i):
            if s == n:
                return True
            if i >= len(powerOfThree) or s > n:
                return False
            if backtracking(s, i + 1) or backtracking(s + powerOfThree[i], i + 1):
                return True
            return False
        return backtracking(0,0)
 
JavaScript:
var checkPowersOfThree = function (n) {
    const pt = [];
    for (let i = 0; 3 ** i <= n; i++) {
        pt.push(3 ** i);
    }
    const go = (idx, n) => {
        if (idx === pt.length) {
            return n === 0;
        }
        return go(idx + 1, n) || go(idx + 1, n - pt[idx]);
    };
    return go(0, n);
};
 

Thống kê chủ đề

Ngày tạo
Vipluckystar,
Người trả lời cuối
Holo code dạo,
Trả lời
7.737
Lượt xem
455.112
Quay lại
Lên đầu trang