/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function (nums, target) {
for (let i = 0; i < nums.length; i++) {
let diff = target - nums[i]
for (let j = i + 1; j < nums.length; j++) {
if (diff == nums[j]) {
return [i, j]
}
}
}
}
/**
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
var twoSum = function (nums, target) {
var temp = []
for (var i = 0; i < nums.length; i++) {
var dif = target - nums[i]
if (temp[dif] != undefined) {
return [temp[dif], i]
}
temp[nums[i]] = i
}
}
14.最长公共前缀
https://leetcode-cn.com/problems/longest-common-prefix
先遍历数组
再遍历数组的第一个字符串,用字符串中的每一个字符和数组中的每一项的对应的该字符串下标相比,不同则跳出循环,两两找出公共前缀,最终结果即为最长公共前缀的长度 j。
截取字符串长度 j 的字符即为最长公共前缀
const strs = [‘flower’, ‘flow’, ‘flight’]
const longestCommonPrefix = function (strs) {
if (strs === null || strs.length === 0) return ‘’
let commonString = ‘’
for (let i = 1; i < strs.length; i++) {
let j = 0
for (; j < strs[0].length && j < strs[i].length; j++) {
if (strs[0][j] !== strs[i][j]) break
}
commonString = strs[0].substring(0, j)
}
return commonString
}
longestCommonPrefix(strs)
18.删除链表的节点
https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof
var deleteNode = function (head, val) {
if (head.val === val) return head.next
let prev = head,
node = prev.next
while (node) {
if (node.val === val) {
prev.next = node.next
}
prev = node
node = node.next
}
return head
}
20.有效的括号
https://leetcode-cn.com/problems/valid-parentheses
该题使用的堆栈(stack)的知识。栈具有先进后出(FILO)的特点。堆栈具有栈顶和栈底之分。所谓入栈,就是将元素压入(push)堆栈;所谓出栈,就是将栈顶元素弹出(pop)堆栈。先入栈的一定后出栈,所以可以利用堆栈来检测符号是否正确配对。