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.
JavaScript:
var insertGreatestCommonDivisors = function(head) {
    const gcd = (a, b) => {
        while (b !== 0) {
            let temp = b;
            b = a % b;
            a = temp;
        }
        return a;
    }

    let cur = head;
    while (cur && cur.next) {
        let next = cur.next;
        cur.next = new ListNode(gcd(cur.val, cur.next.val), next);
        cur = next;
    }

    return head;
};
 
Có cách nào để tìm GCD tối ưu hơn kh nhể mấy bác?

Java:
class Solution {
    public ListNode insertGreatestCommonDivisors(ListNode head) {
        ListNode curr = head;       
        while (curr.next != null) {
            int gcd = findGCD(curr.val, curr.next.val);
            ListNode newNode = new ListNode(gcd, curr.next);
            curr.next = newNode;
            curr = newNode.next;
        }
        return head;
    }

    private int findGCD(int a, int b) {
        if (b == 0) {
            return a;
        }
        return findGCD(b, a % b);
    }
}
 
medium giả vờ rồi
JavaScript:
function gcd(a, b) {
    if (b === 0) {
        return a;
    }
    return gcd(b, a % b);
}

function insertGreatestCommonDivisors(head: ListNode | null): ListNode | null {
    let cur = head;
    while (cur && cur.next) {
        const c = gcd(cur.val, cur.next.val);
        const next = new ListNode(c, cur.next);
        cur.next = next;
        cur = cur.next.next;
    }
    return head;
};
 
C++ nay bài dễ em mới dám đăng, medium bịp :)

C++:
class Solution {
public:
    int greastCommonDivisor(int a, int b){
        while (a!=b){
            if(a>b) a -= b;
            else b-=a;
        }
        return a;
    }
    ListNode* insertGreatestCommonDivisors(ListNode* head){
        ListNode* temp = head;

        while (temp->next){
            ListNode* add = new ListNode(greastCommonDivisor(temp->val, temp->next->val), temp->next);
            temp->next = add;
            temp = temp->next->next;
        }
        return head;
    }
};
 
dkm đến Hà Lội cũng như sông thì đừng nói các tỉnh miền núi. Thời tiết chán chường vc, chiều qua đi về ngập cmn nửa xe :too_sad:
Nhìn thấy sắp thành sông cmnl rồi, đm gặp mấy thằng quan chức kia nó cho khai thác cát lậu dưới sông nữa chứ. Đợt này lũ xong rồi tới sốt xuất huyết dịch bệnh nữa thì toang nặng, thiệt hại kinh tế ko để đâu cho hết
 
Tại sao các ngôn ngữ đều xài node.val mà C++ lại là node->val nhỉ :ah:
Với lại có cái lib nào mà tạo combinations hay permutations như Python ko fence sao biển @seastar
C++:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

class Solution {
public:
    ListNode* insertGreatestCommonDivisors(ListNode* head) {
        ListNode* current = head;
        while (current->next != nullptr)
        {
            int gcdValue = gcd(current->val, current->next->val);
            ListNode* node = new ListNode(gcdValue, current->next);
            current->next = node;
            current = node->next;
        }

        return head;
    }
};
 
Nhìn thấy sắp thành sông cmnl rồi, đm gặp mấy thằng quan chức kia nó cho khai thác cát lậu dưới sông nữa chứ. Đợt này lũ xong rồi tới sốt xuất huyết dịch bệnh nữa thì toang nặng, thiệt hại kinh tế ko để đâu cho hết
e hèm, coi chừng mất thread
kH9BFd2.gif
 
Java:
class Solution {
    public ListNode insertGreatestCommonDivisors(ListNode head) {
        ListNode pointer = head;

        while (pointer != null && pointer.next != null) {
            ListNode next = new ListNode(gcd(pointer.val, pointer.next.val), pointer.next);
            pointer.next = next;
            pointer = next.next;
        }

        return head;
    }

    private int gcd(int x, int y) {
        if (y == 0) return x;
        return gcd(y, x % y);
    }
}
 
Tại sao các ngôn ngữ đều xài node.val mà C++ lại là node->val nhỉ :ah:
Với lại có cái lib nào mà tạo combinations hay permutations như Python ko fence sao biển @seastar
C++:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */

class Solution {
public:
    ListNode* insertGreatestCommonDivisors(ListNode* head) {
        ListNode* current = head;
        while (current->next != nullptr)
        {
            int gcdValue = gcd(current->val, current->next->val);
            ListNode* node = new ListNode(gcdValue, current->next);
            current->next = node;
            current = node->next;
        }

        return head;
    }
};
trong C++ nếu là pointer thì dùng node->val, nếu là object thì dùng node.val

Tạo combinations thì trong std có sẵn đó.
Muốn lấy đc hết combination thì phải sort trước.
 
Python:
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def insertGreatestCommonDivisors(self, head: Optional[ListNode]) -> Optional[ListNode]:
        def gcd(a,b):
            if b == 0:
                return a
            return gcd(b, a % b)
        
        slow = head
        if head.next:
            fast = head.next
            while fast:
                g = gcd(slow.val, fast.val)
                slow.next = ListNode(g, fast)
                slow = fast
                fast = fast.next
            return head
        else:
            return head
 
Java:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode insertGreatestCommonDivisors(ListNode head) {
        ListNode root = new ListNode();
        ListNode temp = root;
        while (head != null) {
            if (head.next == null) {
                temp.next = new ListNode(head.val);
                break;
            }
            temp.next = new ListNode(head.val);
            temp.next.next = new ListNode(greatCommonDivisor(head.val, head.next.val));
            temp = temp.next.next;
            head = head.next;
        }
        return root.next;
    }
    private int greatCommonDivisor(int num1, int num2) {
        if (num1 == 1 || num2 == 1) return 1;
        while (num2 != 0) {
            int tmp = num1 % num2;
            num1 = num2;
            num2 = tmp;
        }
        return num1;
    }
}
 
Sửa lần cuối:
C#:
public class Solution {
    public int LastStoneWeightII(int[] stones) {
        var possibility = new List<int>{ 0 };
        foreach (var t in stones)
        {
            var length = possibility.Count;
            var casePlus = possibility.Select(x => x + t).ToList();
            possibility = possibility.Select(x => Math.Abs(x - t)).Union(casePlus).ToList();
        }

        return possibility.Min();
    }
}

chưa tối ưu lắm, nhờ các thím xem qua chứ mới beat 70% TC
yBBewst.png
 
Java:
class Solution {
    public ListNode insertGreatestCommonDivisors(ListNode head) {
        ListNode curNode = head.next;
        ListNode preNode = head;
        while(curNode!=null){
            int gcd = gcd(curNode.val, preNode.val);
            ListNode inserted = new ListNode(gcd, curNode);
            preNode.next = inserted;
            preNode= curNode;
            curNode = curNode.next;
        }
        return head;
    }
    public int gcd(int a, int b){
        if(b==0) return a;
        return gcd(b,a%b);
    }
}
có ai phải đi chép hàm gcd ko
8brCr6w.png
 
C#:
public class Solution {
    public int LastStoneWeightII(int[] stones) {
        var possibility = new List<int>{ 0 };
        foreach (var t in stones)
        {
            var length = possibility.Count;
            var casePlus = possibility.Select(x => x + t).ToList();
            possibility = possibility.Select(x => Math.Abs(x - t)).Union(casePlus).ToList();
        }

        return possibility.Min();
    }
}

chưa tối ưu lắm, nhờ các thím xem qua chứ mới beat 70% TC
yBBewst.png
Bài này đâu phải là Greedy. Bài này là DP giống Knapsack problem. Còn về cách giải thì đúng rồi. Nhưng nếu muốn code nhìn intuitive hơn thì dùng top-down. (tất nhiên là sẽ chậm hơn)
 
PHP:
class Solution {

    /**
     * @param ListNode $head
     * @return ListNode
     */
    function insertGreatestCommonDivisors($head) {
        $cur = $head;
        $next = $cur->next;

        while ($cur && $next) {
            $common = $this->getGreatedDivisor($cur->val, $next->val);
            $node = new ListNode($common);
            $node->next = $next;
            $cur->next = $node;

            $cur = $next;
            $next = $cur->next;
        }
        
        return $head;
    }

    /**
     * @param int $a
     * @param int $b
     * @return int
     */
    function getGreatedDivisor($a, $b) {
        // a should always be greater than b
        list($a,$b) = ($a < $b) ? [$b, $a] : [$a, $b];

        if ($a % $b === 0) return $b;

        $common = floor($b / 2);
        while ($common > 0) {
            if ($a % $common === 0 && $b % $common === 0) break;
            $common--;
        }

        return $common;
    }
}
 
Bài này đâu phải là Greedy. Bài này là DP giống Knapsack problem. Còn về cách giải thì đúng rồi. Nhưng nếu muốn code nhìn intuitive hơn thì dùng top-down. (tất nhiên là sẽ chậm hơn)
cảm ơn thím, e ngồi nghĩ solution chứ cũng ko rõ pattern, cái knapsack cũng chưa làm nhiều, à với cho e hỏi solution này thì coi là brute force nhỉ?
yBBewst.png
 
Swift:
class Solution {
    func insertGreatestCommonDivisors(_ head: ListNode?) -> ListNode? {
        guard let head else { return head }

        var cur = head
        while let next = cur.next {
            //let num = findCommonDivior(num1: cur.val, num2: next.val)
            let num = gcd(cur.val, next.val)
            cur.next = ListNode(num, next)
            cur = next
        }
        return head
    }
// Tự viết
    func findCommonDivior(num1: Int, num2: Int) -> Int {
        var num1 = num1
        var num2 = num2
        while num1 != num2 {
            if num1 > num2 {
                num1 -= num2
            } else {
                num2 -= num1
            }
        }
        return num1
    }
// Chôm về hiệu năng cao hơn
    private func gcd(_ a: Int, _ b: Int) -> Int {
        var (a, b) = (max(a, b), min(a, b))

        while b > 0 {
            (a, b) = (b, a % b)
        }

        return a
    }
}
 
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.213.821
Quay lại
Lên đầu trang