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

const findMedianSortedArrays = function(nums1, nums2) {
let merged = nums1.concat(nums2);
merged.sort((a, b) => a - b);
let length = merged.length;
if (length % 2 === 0) {
return (merged[length / 2] + merged[(length / 2) - 1]) / 2;
} else {
return merged[Math.floor(length / 2)];
}
};
 
Last edited:
Ngày mai bắt đầu giải lc daily thôi, mong các bác giúp đỡ
sao lại phải chờ ngày mai nhỉ, sao ko phải là ngay bây h làm luôn
JEWoIdl.png
,
 
C#:
public class Solution {
    public int[] Intersect(int[] nums1, int[] nums2) {
        Dictionary<int, int> dict = new Dictionary<int, int>();
        for(int i = 0; i<nums1.Length; i++)
        {
            if(!dict.ContainsKey(nums1[i]))
                dict.Add(nums1[i], 1);
            else
                dict[nums1[i]]++;
        }
        List<int> list = new List<int>();
        for(int i = 0; i<nums2.Length; i++)
        {
            if(dict.ContainsKey(nums2[i]))
            {
                if(dict[nums2[i]] > 0)
                {
                    list.Add(nums2[i]);
                    dict[nums2[i]]--;
                }
            }
        }
        return list.ToArray();
    }
}
 
Python:
class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        ans = []
        countNums1 = defaultdict(int)
        
        for num in nums1:
            countNums1[num] += 1
        
        for num in nums2:
            if countNums1[num] >= 1:
                ans.append(num)
                countNums1[num] -= 1
        
        return ans
 
Python:
class Solution:
    def minDifference(self, nums: List[int]) -> int:
        if len(nums) <= 4:
            return 0
        nums = sorted(nums)
        ans = inf
        # If we make 0 move from the beginning of the array, the min value will be the 0th element (0 - index)
        # If we make 1 move from the beginning of the array, the min value will be the 1st element (0 - index)
        # If we make 2 move from the beginning of the array, the min value will be the 2th element (0 - index)
        # If we make 3 move from the beginning of the array, the min value will be the 3th element (0 - index)
        for move in range(4):
            remaining = 3 - move
            ans = min(nums[-1*(remaining + 1)] - nums[move], ans)
            if ans <= 0:
                return 0

        return ans
 
Last edited:
C-like:
impl Solution {
    pub fn min_difference(mut nums: Vec<i32>) -> i32 {
        let n = nums.len();

        if n < 4 {
            return 0;
        }

        let mut min_diff = i32::MAX;

        for i in 0..=3 {
            let j = 3 - i;

            let (_, &mut cur_max, _) = nums.select_nth_unstable(n - 1 - j);
            let (_, &mut cur_min, _) = nums.select_nth_unstable(i);

            min_diff = min_diff.min(cur_max - cur_min);
        }

        min_diff
    }
}
 
JavaScript:
function minDifference(nums: number[]): number {
    let n = nums.length, k = 0;
    if (n <= 4) return 0;
    nums.sort((a,b) => a- b);
    let res = nums[n-1] - nums[0];
    while (k < 4) {
        res = Math.min(res, nums[n - 1 - (3 - k)] - nums[k])
        k++;
    }
    return res;
};
p/s: dùng min heap và max heap với fix-size 4 thì TC chỉ còn O(n)
 
Last edited:
Python:
class Solution:
    def minDifference(self, nums: List[int]) -> int:
        if len(nums) <= 4:
            return 0
        nums.sort()
        n = len(nums)
        res = nums[-1] - nums[0]
        for i in range(4):
            res = min(nums[n-4+i] - nums[i], res)
        return res
 
Swift:
class Solution {
    func minDifference(_ nums: [Int]) -> Int {
        guard nums.count > 4 else { return 0}
        //[1, 2, 3, 4, 4]
        //[1, 1, 1, 1, 4]
        //[1, 2, 3, 4, 5, 20, 21, 22]
        let nums = nums.sorted()
        var minDiff = nums.last! - nums.first!
        for left in 0...3 {
            let right = nums.count - (3 - left) - 1
            let diff = nums[right] - nums[left]
            minDiff = min(minDiff, diff)
        }
        return minDiff
    }
}
 
Java:
class Solution {
    public int minDifference(int[] nums) {
        int n = nums.length;
        if(n<=3) return 0;
        Arrays.sort(nums);
        int res = Math.min(nums[n-4]- nums[0],nums[n-1]-nums[3]);
        res = Math.min(res,nums[n-3]- nums[1]);
        res =Math.min(res, nums[n-2] - nums[2]);
        return res;
    }
}
 
Python:
class Solution:
    def minDifference(self, nums: List[int]) -> int:
        n = len(nums)
        if n <= 4:
            return 0
        
        nums.sort()
        ans = float("inf")
        for i in range(4):
            ans = min(ans, nums[n - 4 + i] - nums[i])
            if ans == 0:
                return ans
        return ans
 
func minDifference(nums []int) int {
if len(nums) <= 4 {
return 0
}
sort.Ints(nums)
// fmt.Println("nums:", nums)
n := len(nums)
out := nums[n-1] - nums[0]
for i:=0; i < 4;i++ {
out = min(out, nums[n-4+i] - nums)
}
return out
}
func min(a, b int) int {
if a < b {
return a
}
return b
}

 
Python:
class Solution:
    def minDifference(self, nums: List[int]) -> int:
        n = len(nums)
        if n <= 3:
            return 0
            
        smallests = heapq.nsmallest(4, nums)
        largests = heapq.nlargest(4, nums)
        ans = math.inf
        for small in range(4):
            large = 3 - small
            ans = min(ans, largests[large] - smallests[small])

        return ans
 
JavaScript:
var minDifference = function(nums) {
    const n = nums.length
    if (n <= 4) {
        return 0;
    }
    
    for (let i = 0; i < 4; i++) {
        for (let j = i + 1; j < n; j++) {
            if (nums[i] > nums[j]) {
                [nums[i], nums[j]] = [nums[j], nums[i]];
            }
        }
    }
    for (let i = n - 1; i >= n - 4; i--) {
        for (let j = 0; j < i; j++) {
            if (nums[i] < nums[j]) {
                [nums[i], nums[j]] = [nums[j], nums[i]];
            }
        }
    }
    let ans = +Infinity;
    for (let i = 0; i < 4; i++) {
        ans = Math.min(
            ans,
            Math.max(0, nums[n - 1 - 3 + i] - nums[i])
        );
    }
    return ans;
};
 
PHP:
class Solution {

    /**
     * @param Integer[] $nums
     * @return Integer
     */
    function minDifference($nums) {
        if (count($nums) <= 4) return 0;

        sort($nums);
        $ans1 = $nums[count($nums)-4] - $nums[0];
        $ans2 = $nums[count($nums)-3] - $nums[1];
        $ans3 = $nums[count($nums)-2] - $nums[2];
        $ans4 = $nums[count($nums)-1] - $nums[3];

        return min([$ans1, $ans2, $ans3, $ans4]);
    }
}
 
JavaScript:
var minDifference = function(nums) {
    const n = nums.length;
    if (n <= 4) return 0;
    nums.sort((a, b) => a - b);
    return Math.min(nums[n-1] - nums[3], nums[n-2] - nums[2], nums[n-3] - nums[1], nums[n-4] - nums[0]);
};
 
Java:
class Solution {
    public int minDifference(int[] nums) {
        int len = nums.length;
        if(nums.length <=4) return 0;
        Arrays.sort(nums);
        int min = Integer.MAX_VALUE;
        for(int i =0;i<=3;i++){
            int res = nums[len-4+i]-nums[i];
            min = Math.min(min,res);
        }
        return min;
    }
}
Bài này phải là easy mới đúng
gq7t32C.png
 
JavaScript:
/**
 * @param {number[]} nums
 * @return {number}
 */
var minDifference = function(nums) {
    if(nums.length < 5) return 0

    nums.sort((a, b) => a - b)

    console.log(nums)

    let min = Infinity

    let l = 0
    let r = l + nums.length - 1 - 3
    while(r < nums.length) {
        min = Math.min(min, nums[r] - nums[l])
        l += 1
        r = l + nums.length - 1 - 3
    }

    return min
};

xjIzSG9.png
 
Back
Top