[LeetCode 三数之和 && 等式方程的可满足性] | 刷题打卡

88 阅读1分钟

15. 三数之和

leetcode-cn.com/problems/3s…

  • 先排序 固定一个然后双指针
/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var threeSum = function (nums) {
    nums = nums.sort((a, b) => a - b)
    const res = []
    for (let i = 0; i < nums.length - 2; i++) {
        if(nums[i] > 0){
            break
        }
        // 去重
        if (i > 0 && nums[i] === nums[i - 1]) {
            continue
        }
        for (let left = i + 1, right = nums.length - 1; left < right;) {
            const fixedNum = -nums[i]
            if (fixedNum < 0) {
                break
            }
            let sum = nums[left] + nums[right]
            if (sum === fixedNum) {
                // 去重
                if(nums[left] === nums[left -1] && (left-1) > i){
                    left ++
                    continue
                }
                res.push([nums[i], nums[left], nums[right]])
                left++
            }if (sum > fixedNum) {
                right--
            } else {
                left++
            }
        }
    }
    return res
};

990. 等式方程的可满足性

leetcode-cn.com/problems/sa…

  • 并查集
/**
 * @param {string[]} equations
 * @return {boolean}
 */

class DisJointSet {

    rank = []
    parent = []

    constructor(size){
        for(let i=0;i<size;i++){
            this.parent[i] = i
            this.rank[i] = 1
        }
    }
    // 找出节点p的顶点 也就是所属的集合
    find(p){
        if(p<0 || p>(this.parent.length-1)){
            throw new Error("invalid element")
        }
        while(this.parent[p] !==p){
            // 路径压缩 在找的过程中将树的高度剪低
            this.parent[p] = this.parent[this.parent[p]]
            p = this.parent[p]
        }
        return p
    }
    merge(p,q){
        let pRoot = this.find(p)
        let qRoot = this.find(q)
        if(pRoot === qRoot){
            return
        }
        // 基于rank的优化 将高度较小的树嫁接到高度高的树 防止在合并的过程中树的高度增加
        if(this.rank[pRoot] < this.rank[qRoot]){
            this.parent[pRoot] = qRoot
        }else if(this.rank[pRoot] > this.rank[qRoot]){
            this.parent[qRoot] = pRoot
        }else{
            this.parent[qRoot] = pRoot
            this.rank[pRoot] ++ 
        }
    }
    // 并查集大小
    getsize(){
        return this.parent.length
    }
    // 两个集合是否联通
    isConnected(p,q){
        return this.find(p) === this.find(q)
    }

}


var equationsPossible = function(equations) {
    const djs = new DisJointSet(27)

    for(let i =0;i<equations.length;i++){
        if(equations[i][1] === "="){
            djs.merge(equations[i].charCodeAt(0) - 97 ,equations[i].charCodeAt(3) - 97)
        }
    }

    for(let i=0;i<equations.length;i++){
        if(equations[i][1] === "!"){
            if(djs.isConnected(equations[i].charCodeAt(0) - 97,equations[i].charCodeAt(3) - 97)){
                return false
            }
        }
    }
    return true

};