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

C++:
int findMaxK(vector<int>& nums) {
    unordered_set<int> s;
    int ret = -1;
    for(auto e : nums) {
        if (s.count(-e))
            ret = max(ret, abs(e));
        else
            s.insert(e);
    }
    return ret;
}
 
Java:
class Solution {
    public int findMaxK(int[] nums) {
        Set<Integer> negative = new HashSet<>();

        for (int num: nums) {
            if (num < 0) {
                negative.add(num);
            }
        }

        int max = -1;

        for (int num: nums) {
            if (num > max && negative.contains(-num)) {
                max = num;
            }
        }

        return max;
    }
}
Đề nghị leetcode cho câu hard, dễ quá toi ko có động lực làm :rolleyes:
 
Java:
public int findMaxK(int[] nums) {
    int max = 0;
    Set<Integer> set = new TreeSet<>();
    for (int n1 : nums) {
        int n2 = -n1;
        if (set.contains(n2)) {
            max = Math.max(max, Math.max(n1, n2));
        }
        set.add(n1);
    }
    return max == 0 ? -1 : max;
}
 
Java:
class Solution {
    public int findMaxK(int[] nums) {
        Set<Integer> negative = new HashSet<>();

        for (int num: nums) {
            if (num < 0) {
                negative.add(num);
            }
        }

        int max = -1;

        for (int num: nums) {
            if (num > max && negative.contains(-num)) {
                max = num;
            }
        }

        return max;
    }
}
Đề nghị leetcode cho câu hard, dễ quá toi ko có động lực làm :rolleyes:
Thích thì try hard tối ưu hết mức có thể đi. Bài này còn dùng bitset để tối ưu :ops:
 
Quay trở lại sau kì nghỉ lễ :ah:
JavaScript:
function findMaxK(nums: number[]): number {
    let res = -1;
    const set = new Set();
    for (const num of nums) {
        set.add(num)
        if (set.has(num * -1)) res = Math.max(res, Math.abs(num))
    }
    return res; 
};
 
bài hôm trước có số 2000, bài hôm nay 2001

Code:
use std::collections;
use std::cmp;

impl Solution {
    pub fn find_max_k(nums: Vec<i32>) -> i32 {
        let n = nums.len();
        let mut hash_set = vec![false; 2001];

        for &a in &nums {
            hash_set[(a + 1000) as usize] = true;
        }

        let mut max = -1;
        for &a in &nums {
            if (a > 0 && hash_set[(1000 - a) as usize]) {
                max = cmp::max(max, a);
            }
        }

        max
    }
}
 
Last edited:
Python:
class Solution:
    def findMaxK(self, nums: List[int]) -> int:
        have_positive = [0] * 1001 # have_positive[n] = 1 if n in nums
        have_negative = [0] * 1001 # have_negative[n] = 1 if -n in nums
        
        result = -1
        
        for num in nums:
            if num > 0:
                have_positive[num] = 1
                if have_negative[num] and num > result:
                    result = num
            elif num < 0:
                have_negative[-num] = 1
                if have_positive[-num] and -num > result:
                    result = -num
                    
        return result
 
class Solution(object):
def findMaxK(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
largestNum = -1
nums = set(nums)
for num in nums:
if -1 * num in nums :
largestNum = max(num, abs(largestNum))
return largestNum
 
public class Solution {
public int FindMaxK(int[] nums) {
Dictionary<int,int> map = new Dictionary<int, int>();
int max = -1;
int temp;
foreach(int val in nums){
if(map.TryGetValue(val*-1,out temp) && Math.Abs(val) > max){
max = Math.Abs(val);
}else {
map.TryAdd(val,val * -1);
}
}
int key = nums[nums.Length-1];
if(map.TryGetValue(key*-1,out temp) && Math.Abs(key) > max){
max = temp;
}
return max;

}
}
 
Easy sau một kì nghỉ lễ dài, hợp lí
Java:
class Solution {
    fun findMaxK(nums: IntArray): Int {
        var ans = -1
        val numsSet = nums.toSet()
        nums.forEach {
            if (it > 0 && -it in numsSet) {
                ans = max(it, ans)
            }
        }
        return ans
    }
}
 
Java:
class Solution {
    public int findMaxK(int[] nums) {
        int ans =-1;
        boolean[] check = new boolean[2002];

        for(int num:nums){
            check[num+1000] = true;
            if(check[num+1000] && check[-num+1000]) {
                ans= ans<Math.abs(num)? Math.abs(num):ans;
            }
        }
        return ans;
    }
}
 
JavaScript:
var findMaxK = function(nums) {
    const set = new Set(nums);
    let res = -1;
    for (const n of nums) {
        if (n > res && set.has(-n)) res = n;
    }
    return res;
};
 
Java:
class Solution {
    public int findMaxK(int[] nums) {
        Set<Integer> negative = new HashSet<>();

        for (int num: nums) {
            if (num < 0) {
                negative.add(num);
            }
        }

        int max = -1;

        for (int num: nums) {
            if (num > max && negative.contains(-num)) {
                max = num;
            }
        }

        return max;
    }
}
Đề nghị leetcode cho câu hard, dễ quá toi ko có động lực làm :rolleyes:
tính mở vào phần similar kiếm thêm câu nữa làm
1714617112673.png

JEWoIdl.png
hehe boai
nghĩ 1 hồi thấy nó cấn cấn mở topic ra, ez giả cầy r
KE5ti7l.png
1714617173486.png
 
Last edited:
tính mở vào phần similar kiếm thêm câu nữa làm
View attachment 2470622
JEWoIdl.png
hehe boai
nghĩ 1 hồi thấy nó cấn cấn mở topic ra
KE5ti7l.png
View attachment 2470626
bruteforce thôi

Code:
use std::cmp;
use std::str;

impl Solution {
    pub fn longest_nice_substring(s: String) -> String {
        let bytes = s.as_bytes();
        let n = bytes.len();

        let mut max_i = 0;
        let mut max_j = 0;

        for i in 0..n {
            let mut lower_case_mask = 0u32;
            let mut upper_case_mask = 0u32;

            for j in i..n {
                if (bytes[j] >= b'a' && bytes[j] <= b'z') {
                    let char_mask = 1 << (bytes[j] - b'a');
                    lower_case_mask |= char_mask;
                }

                if (bytes[j] >= b'A' && bytes[j] <= b'Z') {
                    let char_mask = 1 << (bytes[j] - b'A');
                    upper_case_mask |= char_mask;
                }

                if (lower_case_mask ^ upper_case_mask == 0 && j + 1 - i > max_j - max_i) {
                    max_i = i;
                    max_j = j + 1;
                }
            }
        }

        unsafe { str::from_utf8_unchecked(&bytes[max_i..max_j]) }.to_string()
    }
}
 
bruteforce thôi

Code:
use std::cmp;
use std::str;

impl Solution {
    pub fn longest_nice_substring(s: String) -> String {
        let bytes = s.as_bytes();
        let n = bytes.len();

        let mut max_i = 0;
        let mut max_j = 0;

        for i in 0..n {
            let mut lower_case_mask = 0u32;
            let mut upper_case_mask = 0u32;

            for j in i..n {
                if (bytes[j] >= b'a' && bytes[j] <= b'z') {
                    let char_mask = 1 << (bytes[j] - b'a');
                    lower_case_mask |= char_mask;
                }

                if (bytes[j] >= b'A' && bytes[j] <= b'Z') {
                    let char_mask = 1 << (bytes[j] - b'A');
                    upper_case_mask |= char_mask;
                }

                if (lower_case_mask ^ upper_case_mask == 0 && j + 1 - i > max_j - max_i) {
                    max_i = i;
                    max_j = j + 1;
                }
            }
        }

        unsafe { str::from_utf8_unchecked(&bytes[max_i..max_j]) }.to_string()
    }
}
bit manipulation vẫn là quá sức đối với e bác à
yBBewst.png
 
Python:
class Solution:
    def findMaxK(self, nums: List[int]) -> int:
        existed = {}
        for num in nums:
            if num < 0:
                existed[num] = True
        result = -1
        for num in nums:
            if num > result and (0 - num) in existed:
                result = num
        return result
 
Dùng binary search tree.
Java:
public int findMaxK(int[] nums) {
        Arrays.sort(nums);
        int idx = nums.length - 1;
        while (idx > 0 && nums[idx] > 0) {
            boolean isFound = found(nums, -nums[idx]);
            if (isFound) return nums[idx];
            idx--;
        }

        return -1;
    }

    boolean found(int[] nums, int num) {
        int left = 0;
        int right = nums.length - 1;
        while (right >= left) {
            int mid = (right + left) / 2;

            if (num < nums[mid]) {
                right = mid - 1;
            } else if (num > nums[mid]) {
                left = mid + 1;
            } else if (num == nums[mid]) {
                return true;
            }
        }

        return false;
    }
 
Java:
class Solution {
    public int findMaxK(int[] nums) {
      Set<Integer> setNegativeNums = new HashSet<>();
      int max = -1;
      for (int num : nums) {
        if (setNegativeNums.contains(-num)) {
          max = Math.max(max, Math.abs(num));
        }
        setNegativeNums.add(num);
      }
      return max;
    }
}
 
JavaScript:
function findMaxK(nums: number[]): number {
    let set = new Set<number>();
    let res = -1;

    for (let num of nums) {
        if (set.has(num * -1) && Math.abs(num) > res) {
            res = Math.abs(num)
        }

        set.add(num)
    }

    return res
};
 
Back
Top