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.
@freedom.9 Thím có thể cho e vài tips live coding không ạ. Em ít kinh nghiệm phần live code này, lần gần đây nhất live code thì e bị run và under perform. Cảm ơn thím :pudency:
Edit: T5 này e live code =((
cái này phải luyện dần dần và cần có thời gian để tiến bộ, chứ t5 này pv mà bây h mới hỏi thì train sao mà kịp, thôi cứ đi pv, fail nhiều nó cũng tự lên trình.
 
Bớt dùm đơn 1 hòn
xjIzSG9.png
nickname gì nghe gớm vậy. :doubt:
 
Java:
class Solution {
    public boolean canArrange(int[] arr, int k) {
        Map<Integer, Integer> map = new HashMap<>();

        for (int num : arr) {
            int remainder = (num % k + k) % k;
            int need = (k - remainder) % k;

            if (map.getOrDefault(need, 0) != 0) {
                map.put(need, map.get(need) - 1);
            } else {
                map.put(remainder, map.getOrDefault(remainder, 0) + 1);
            }
        }

        for (int elem : map.values()) {
            if (elem != 0) {
                return false;
            }
        }

         return true;
    }
}
 
C-like:
impl Solution {
    pub fn can_arrange(arr: Vec<i32>, k: i32) -> bool {
        let freq = arr
            .iter()
            .fold(std::collections::HashMap::new(), |mut freq, num| {
                let num = (k + num % k) % k;
                if num > k - num {
                    *freq.entry(k - num).or_insert(0) -= 1;
                } else {
                    if num == 0 || num == k - num {
                        freq.entry(num)
                            .and_modify(|v| {
                                if *v != 0 {
                                    *v = 0
                                } else {
                                    *v = 1
                                }
                            })
                            .or_insert(1);
                    } else {
                        *freq.entry(num).or_insert(0) += 1;
                    }
                }
                freq
            });
        freq.values().all(|v| *v == 0)
    }
}
 
C-like:
impl Solution {
    pub fn can_arrange(arr: Vec<i32>, k: i32) -> bool {
        let uk = k as usize;
        let mut mod_freqs = vec![0; uk];

        for num in arr {
            mod_freqs[num.rem_euclid(k) as usize] += 1;
        }

        if mod_freqs[0] % 2 != 0 {
            return false;
        }

        for i in 1..=(uk / 2) {
            if mod_freqs[i] != mod_freqs[uk - i] {
                return false;
            }
        }

        true
    }
}
 
Sửa lần cuối:
@freedom.9 Thím có thể cho e vài tips live coding không ạ. Em ít kinh nghiệm phần live code này, lần gần đây nhất live code thì e bị run và under perform. Cảm ơn thím :pudency:
Edit: T5 này e live code =((
Live coding thì cứ bình tĩnh, vô contest mà tập luyện nó giới hạn về mặt thời gian + câu hỏi mới nêm còn run hơn live coding thôi fence.
Muốn ko run thì chỉ có practice thôi, chưa practice kĩ thì thì toang như thường, practice kĩ thì toàn nhăm nhe đấm interviewer
zFNuZTA.gif


via theNEXTvoz for iPhone
 
Live coding thì cứ bình tĩnh, vô contest mà tập luyện nó giới hạn về mặt thời gian + câu hỏi mới nêm còn run hơn live coding thôi fence.
Muốn ko run thì chỉ có practice thôi, chưa practice kĩ thì thì toang như thường, practice kĩ thì toàn nhăm nhe đấm interviewer
zFNuZTA.gif


via theNEXTvoz for iPhone
Cảm ơn thím :love:
 
Python:
class Solution:
    def arrayRankTransform(self, arr: List[int]) -> List[int]:
        sortedRanked = sorted(set(arr))
        rank = 1
        sortedRankedMap = defaultdict(int)
        for i in range(len(sortedRanked)):
            sortedRankedMap[sortedRanked[i]] = i + 1
        return [sortedRankedMap[num] for num in arr]
 
Python:
class Solution:
    def arrayRankTransform(self, arr: List[int]) -> List[int]:
        n = len(arr)
        ans = [0]*n
        arr = [[arr[i], i] for i in range(n)]
        arr = sorted(arr)
        currentRank = 0
        for i in range(n):
            if i != 0 and arr[i][0] == arr[i-1][0]:
                ans[arr[i][1]] = currentRank
            else:
                currentRank += 1
                ans[arr[i][1]] = currentRank

        return ans
 
C++:
class Solution {
public:
    vector<int> arrayRankTransform(vector<int>& arr) {
        vector<int> tmp = arr;
        sort(tmp.begin(), tmp.end());

        map<int, int> rank;
        int rnk = 0;
        for (int i = 0; i < tmp.size(); i++) {
            if (!rank[tmp[i]]) {
                rnk++;
                rank[tmp[i]] = rnk;
            }
        }

        vector<int> ans(arr.size(), 0);

        for (int i = 0; i < arr.size(); i++) {
            ans[i] = rank[arr[i]];
        }

        return ans;
    }
};
 
code rác :too_sad:
JavaScript:
function arrayRankTransform(arr: number[]): number[] {
    const n = arr.length
    const res = new Array(n).fill(1);
    const map = new Map();
    const newArr = [...arr].sort((a, b) => b - a);
    for (const num of newArr) {
        map.set(num, (map.get(num) || 0) + 1);
    }
    let max = map.size;
    for (const key of map.keys()) {
        map.set(key, max--)
    }
    for (let i = 0; i < n; i++) {
        res[i] = map.get(arr[i])
    }
    return res;
};
 
Java:
class Solution {
    public int[] arrayRankTransform(int[] arr) {
        HashMap<Integer, Integer> map = new HashMap<>();
        int[] copy = new int[arr.length];
        
        for (int i = 0; i < arr.length; i++) {
            copy[i] = arr[i];
        }

        Arrays.sort(copy);
        int rank = 1;

        for (int i : copy) {
            if (!map.containsKey(i))
                map.put(i, rank++);
        }

        for(int i = 0; i < arr.length; i++) {
            arr[i] = map.get(arr[i]);
        }

        return arr;
    }
}
 
Java:
class Solution {
    public int[] arrayRankTransform(int[] arr) {
        int[] res = new int[arr.length];
        int[] newArr = Arrays.copyOfRange(arr, 0, arr.length);
        Arrays.sort(newArr);
        Map<Integer, Integer> map = new HashMap<>();
        int index = 0;
        for (int i : newArr) {
            if (map.containsKey(i)) {
                continue;
            }
            map.put(i, index++);
        }
        index = 0;
        for (int i : arr) {
            res[index++] = map.get(i) + 1;
        }
        return res;
    }
}
Python:
class Solution:
    def arrayRankTransform(self, arr: List[int]) -> List[int]:
        res = []
        newArr = arr.copy()
        newArr.sort()
        map = {}
        idx = 0
        for i in range(0, len(newArr)):
            if map.get(newArr[i]) != None: continue
            map[newArr[i]] = idx
            idx += 1
        for i in arr:
            key = map[i] + 1
            res.append(key)
        return res
xjIzSG9.png
last updated
 
Sửa lần cuối:
Swift:
class Solution {
    func arrayRankTransform(_ arr: [Int]) -> [Int] {
        let sorted = arr.sorted()
        var dict:[Int:Int] = [:]
        var rank = 1
        for num in sorted {
            if dict[num] == nil {
                dict[num] = rank
                rank += 1
            }
        }
        return arr.map{ dict[$0]! }
    }
}
 
Java:
class Solution {
    public int[] arrayRankTransform(int[] arr) {
        int n = arr.length;
        int[] res = new int[n];
        int[][] map = new int[n][2];
        for(int i =0 ; i < n;i++){
            map[i][0] = arr[i];
            map[i][1]=i;
        }
        Arrays.sort(map, (a,b)-> a[0]-b[0]);
        int last = Integer.MIN_VALUE;
        int rank =0;
        for(int i =0;i<arr.length;i++){
            if(map[i][0]!=last){
                rank++;
            }
            last=map[i][0];
            res[map[i][1]] = rank;
        }
        return res;
    }
}
 
PHP:
class Solution {

    /**
     * @param Integer[] $arr
     * @return Integer[]
     */
    function arrayRankTransform($arr) {
        $hash = [];
        foreach ($arr as $k => $v) {
            $hash[$v] = $k;
        }

        $hash = array_flip($hash);
        sort($hash);
        $hash = array_flip($hash);

        $ans = [];
        foreach ($arr as $k => $v) {
            $ans[] = $hash[$v]+1;
        }

        return $ans;
    }
}
 
Java:
class Solution {
    public int[] arrayRankTransform(int[] arr) {
        int[] res = new int[arr.length];
        int[] newArr = Arrays.copyOfRange(arr, 0, arr.length);
        Arrays.sort(newArr);
        Map<Integer, Integer> map = new HashMap<>();
        int index = 0;
        for (int i : newArr) {
            if (map.containsKey(i)) {
                continue;
            }
            map.put(i, index++);
        }
        index = 0;
        for (int i : arr) {
            res[index++] = map.get(i) + 1;
        }
        return res;
    }
}
Python:
class Solution:
    def arrayRankTransform(self, arr: List[int]) -> List[int]:
        res = []
        newArr = arr.copy()
        newArr.sort()
        map = {}
        for i in range(0, len(newArr)):
            map[newArr[i]] = i
        for i in arr:
            key = list(map.keys()).index(i) + 1
            res.append(key)
        return res
xjIzSG9.png
cái đoạn key = list(map……. kia thành O n^2
key = map[ i ] + 1 thôi

via theNEXTvoz for iPhone[/i]
 
Sửa lần cuối:
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.669
Quay lại
Lên đầu trang