15. 三数之和
leetcode-cn.com/problems/3s…
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…
class DisJointSet {
rank = []
parent = []
constructor(size){
for(let i=0;i<size;i++){
this.parent[i] = i
this.rank[i] = 1
}
}
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
}
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
};