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.
Java:
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int i = 0;
        int j = 0;
        int len = 0;
        while (i < nums1.length && j < nums2.length) {
            if (nums1[i] == nums2[j]) {
                nums1[len] = nums1[i];
                len++;
                i++;
                j++;
            } else if (nums1[i] < nums2[j]) {
                i++;
            } else {
                j++;
            }
        }
        int[] res = new int[len];
        for (int index = 0; index < len; index++) {
            res[index] = nums1[index];
        }
        return res;
    }
}
 
Sửa lần cuối:
Java:
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int i  =0;
        int j =0 ;
        int len=0;
        while(i<nums1.length && j<nums2.length){
            if(nums1[i]==nums2[j]){
                nums1[len] = nums1[i];
                len++;
                i++;j++;
            }
            else if(nums1[i]<nums2[j]){
               i++;
            }
            else{
               j++;
            }
        }
        int[] res = new int[len];
        for(int index =0 ; index < len ; index++){
            res[index]=nums1[index];
        }
        return res;
    }
}
góc trên bên phải có nút format đó fen, sao ko format lại nhìn cho nó gọn.
 
PHP:
class Solution {

    /**
     * @param Integer[] $nums1
     * @param Integer[] $nums2
     * @return Integer[]
     */
    function intersect($nums1, $nums2) {
        $dictNums2 = [];
        foreach ($nums2 as $n) {
            if (!isset($dictNums2[$n])) $dictNums2[$n] = 0;
            $dictNums2[$n]++;
        }

        $intersecion = [];
        foreach ($nums1 as $n) {
            if (!isset($dictNums2[$n]) || $dictNums2[$n] < 1) continue;

            $intersecion[] = $n;
            $dictNums2[$n]--;
        }

        return $intersecion;
    }
}
 
Sửa lần cuối:
Java:
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        int i1 = 0, i2 = 0;
        List<Integer> intersectNums = new ArrayList<>();
        while (i1 != nums1.length && i2 != nums2.length) {
            if (nums1[i1] > nums2[i2]) {
                i2++;
            } else if (nums1[i1] < nums2[i2]) {
                i1++;
            } else {
                intersectNums.add(nums1[i1]);
                i1++;
                i2++;
            }
        }

        int[] answer = new int[intersectNums.size()];
        for (int i = 0; i < intersectNums.size(); i++) {
            answer[i] = intersectNums.get(i);
        }

        return answer;
    }
}

Follow up không đổi :v chỉ là giảm từ độ phức tạp từ O(nlogn) xuống O(n) và SC giảm từ O(log) xuống O(1). Không phụ thuộc và value range của nums1 và nums2
 
Java:
class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
        
        if(nums1.length > nums2.length){
            return intersect(nums2, nums1);
        }

         HashMap<Integer, Integer> m = new HashMap<>();
        for (int n: nums1){
            m.put(n, m.getOrDefault(n,0) +1);
        }
        int k = 0;
        for (int n: nums2){
            int cnt = m.getOrDefault(n, 0);
            if (cnt > 0 ){
                nums1[k++] = n;
                m.put(n, cnt -1);
            }
        }
        return Arrays.copyOfRange(nums1, 0, k);
}
}
1719899619089.png
 
C-like:
impl Solution {
    pub fn intersect(nums1: Vec<i32>, nums2: Vec<i32>) -> Vec<i32> {
        #[inline]
        fn opt_get_mut<'t, T>(v: &'t mut [T], i: i32) -> &'t mut T {
            unsafe { v.get_unchecked_mut(i as usize) }
        }
        #[inline]
        fn opt_get<'t, T>(v: &'t mut [T], i: i32) -> &'t T {
            unsafe { v.get_unchecked(i as usize) }
        }
        let (mut e1, mut e2) = (vec![0; 1001], vec![0; 1001]);
        
        nums1.into_iter().for_each(|i| {
            let ei = opt_get_mut(&mut e1, i);
            *ei = *ei + 1;
            
        });
        nums2.into_iter().for_each(|i| {
            let ei = opt_get_mut(&mut e2, i);
            *ei = *ei + 1;
        });
        return (0..1001).map(|i| {
            let (&ei1, &ei2) = (opt_get(&mut e1, i), opt_get(&mut e2, i));
            let min = if ei1 < ei2 { ei1 } else { ei2 };
            vec![i; min]
        }).collect::<Vec<_>>().concat();
    }
}
 
Sửa lần cuối:
bài dễ quá thì phải làm khó lên các bạn à, thay vì copy vài integer thì lấy reference ra, thay vì lấy reference ra trực tiếp thì phải bỏ vào hàm, lúc duyệt qua frequency map cho hai array thì thay vì viết loop để thêm element vào kết quả thì alloc thêm array tạm rồi lấy element từ array tạm nhét vào trong kết quả 💪

phải làm vầy để cho thế giới biết mình não to chứ 🧠
 
bài dễ quá thì phải làm khó lên các bạn à, thay vì copy vài integer thì lấy reference ra, thay vì lấy reference ra trực tiếp thì phải bỏ vào hàm, lúc duyệt qua frequency map cho hai array thì thay vì viết loop để thêm element vào kết quả thì alloc thêm array tạm rồi lấy element từ array tạm nhét vào trong kết quả 💪

phải làm vầy để cho thế giới biết mình não to chứ 🧠
thay vì dài dòng ntn thì t viết 1 dòng được k? :doubt:

Python:
return (Counter(nums1) & Counter(nums2)).elements()
 
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)];
}
};
 
Sửa lần cuối:
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
 
Sửa lần cuối:
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)
 
Sửa lần cuối:
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
 
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.212.973
Quay lại
Lên đầu trang