括号序列
给出一个仅包含字符'(',')','{','}','['和']',的字符串,判断给出的字符串是否是合法的括号序列 括号必须以正确的顺序关闭,"()"和"()[]{}"都是合法的括号序列,但"(]"和"([)]"不合法。
利用栈的思维,实现代码如下
function isValid(s) {
let len = s.length
if (len <= 1) return false;
let stack = [];
let pair = {
'{': '}',
'[': ']',
'(': ')'
}
for (let i = 0; i < len; i++) {
let item = s[i];
if (item === '(' || item === '[' || item === '{') {
stack.push(item);
} else {
if (pair[stack[stack.length - 1]] !== item) return false;
stack.pop();
}
}
return stack.length <= 0;
}
console.log(isValid("[][]()[]{}")) // true
console.log(isValid("[)")) // false
console.log(isValid("[}")) // false
console.log(isValid("[[[)))")) // false
console.log(isValid("[()]")) // true
反转链表
输入一个链表,反转链表后,输出新链表的表头。
使用迭代方式
function ReverseList(pHead) {
if (!pHead || !pHead.next) {
return pHead;
}
let newHead = null;
while(pHead) {
let temp = pHead.next;
pHead.next = null;
newHead = pHead;
pHead = temp;
}
return newHead;
}
// 输入:1->2->3
// 输出:3->2->1
最小的K个数
输入n个整数,找出其中最小的K个数。例如输入4,5,1,6,2,7,3,8这8个数字,则最小的4个数字是1,2,3,4。
先排序数组,然后返回数组的前K个值
function GetLeastNumbers_Solution(input, k) {
if (input.length < k) return [];
// 先通过快速排序去排序
function quickSort(input) {
if (input.length <= 1) return input;
let midIndex = Math.floor(input.length / 2);
let mid = input.splice(midIndex, 1)[0];
let left = [];
let right = [];
for (let i = 0; i < input.length; i++) {
const element = input[i];
if (element < mid) {
left.push(element);
} else {
right.push(element);
}
}
return quickSort(left).concat([mid],quickSort(right));
}
input = quickSort(input);
return input.slice(0, k)
}
console.log(GetLeastNumbers_Solution([1,2,3,4,51,2], 5));
合并有序链表
将两个有序的链表合并为一个新链表,要求新的链表是通过拼接两个链表的节点来生成的。
function ListNode(val) {
this.val = val;
this.next = null;
}
function mergeTwoLists(l1, l2) {
let root = new ListNode(-1);
let now = root;
while (l1 || l2) {
if (!l1 || !l2) {
now.next = l1 ? l1 : l2;
break;
}
if (l1.val < l2.val) {
now.next = l1;
l1 = l1.next;
} else {
now.next = l2;
l2 = l2.next;
}
now = now.next;
}
return root.next;
}