演算法 LeetCode刷題

2022-02-19 08:46:33 字數 3806 閱讀 4552

given[1,3],[2,6],[8,10],[15,18],

return[1,6],[8,10],[15,18].

關鍵就是a[1]>=b[0]也就是array[i-1][1]>=array[i][0]

const merge = array => 

} return array

}console.log(merge([[1, 3], [8, 10], [2, 6], [15, 18]]))

//[ [ 1, 6 ], [ 8, 10 ], [ 15, 18 ] ]

str.length % s.length

const repeated = s => 

if (emptystr == s) }}

return false

}console.log(repeated('abab'))

//走樓梯 小孩最多走1,2,3個,問總樓梯數n,有多少種走法

dp f(x,y)=f(x,y-1)+f(x-1,y)

const recursion = n =>

console.log(recursion(3)) //4

//f(x,y)=f(x-1,y)+f(x,y-1)

const solve = (x, y) =>

console.log(solve(2, 3))

題目

[1,2,3,4]

1 2 3

4"1(2(4))(3()())" 兩個括號在一起就可以省略

"1(2(4))(3)"

[1,2,3,null,4]

1 2 3

4"1(2()(4))(3)"

let tree=,

right:

},right:

}}const tree2str = t =>

if (t.left == null && t.right == null)

if (t.left == null)

if (t.right == null)

return t.val + '(' + tree2str(t.left) + ')' + '(' + tree2str(t.right) + ')'

}console.log(tree2str(tree))

n      組合

1 ()

2 ()() (())

3 ()()() (()()) ((()))

const printpar = (l, r,s='', result=) =>

if (l > 0)

if (r > 0 && l < r)

return result

}console.log(printpar(3, 3))

// 'abcab'  =>  'abc'

// 'abcabc' => 'abc'

// 'abcdababab' =>'abcd'

//計數排序

const solution = (s) =>

let hash = array.from(,v=>0);

let begin = 0,

end = 0;

let repeat = 0,

res = 0;

while (end < s.length)

while (repeat > 0)

}//總次數減去不重複的 5-2=3

res = math.max(res, end - begin)

} console.log(hash)

return res

}console.log(solution('abcab'))

輸入: 

1/ \

0 2

l = 1

r = 2

輸出: 1\

2輸入:

3/ \

0 4\2

/1 l = 1

r = 3

輸出: 3/

2

/ 1二叉搜尋樹,進行範圍限制

//雙指標

邏輯使用棧遍歷輸入字串

如果當前字串為左括號時,則將壓入棧中

如果遇到右括號時:

* 如果棧不為空且為對應的左半括號,則取出棧頂元素,繼續迴圈

* 若此時棧為空,則直接返回false

* 若不為對應的左半括號,直接返回false

const isvalid = s => ',

'[': ']',

'(': ')'

};for (let i in s) else

}} if(stack.length>0) return false

return valid

}console.log(isvalid('()'))

思路使用快慢指標來記錄遍歷的座標

const removeduplicates = nums => 

}return slow+1

}console.log(removeduplicates([1, 2,3,4,4,4,4,4,5,6,7,8]))

const merge = (num1, num2) => 

if (num2.length == 0)

if (num1[0] >= num2[0]) else

} return ret

}簡潔版

const merge = (nums1, m, nums2, n) => else

} while (i2 >= 0)

return nums1

}

const maxdepth=root=>

演算法題 LeetCode刷題(五)

資料結構和演算法是程式設計路上永遠無法避開的兩個核心知識點,本系列 演算法題 旨在記錄刷題過程中的一些心得體會,將會挑出leetcode等最具代表性的題目進行解析,題解基本都來自於leetcode官網 本文是第五篇。給定乙個非負整數陣列,你最初位於陣列的第乙個位置。陣列中的每個元素代表你在該位置可以...

leetcode刷題 演算法思想

167 兩數之和 ii 輸入有序陣列 input numbers target 9output index1 1,index2 2我的弱智解法 全部遍歷一遍 class solution return array 優質解法 使用雙指標,乙個指標指向值較小的元素,乙個指標指向值較大的元素。指向較小元素...

LeetCode刷題 演算法篇

暴力解法 class solution def twosum self,nums list int target int list int i 0 while i j i 1 while j if nums i nums j target return i,j j 1i 1 return none ...