leetcode简单(数组,字符串,链表):[1, 9, 13, 14, 20, 21, 26, 27, 35, 58]
目录
1. 两数之和
var twoSum = function(nums, target) {
// 第一种
// var len = nums.length
// for (var i = 0; i < len; i++) {
// for (var j = i + 1; j < len; j++) {
// if (target - nums[i] == nums[j]) {
// return [i, j]
// }
// }
// }
// 第二种
var map = new Map()
for (let i = 0; i < nums.length; i++) {
var comNum = target - nums[i]
if (map.has(comNum)) {
return [map.get(comNum), i]
} else {
map.set(nums[i], i)
}
}
return []
};
9. 回文数
var isPalindrome = function(x) {
var str = '' + x
var left = 0
var right = str.length - 1
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false
}
left++
right--
}
return true
};
13. 罗马数字转整数
var romanToInt = function(s) {
var roman = ['I', 'V', 'X', 'L', 'C', 'D', 'M', 'IV', 'IX', 'XL', 'XC', 'CD', 'CM']
var num = [1, 5, 10, 50, 100, 500, 1000, 4, 9, 40, 90, 400, 900]
var res = 0
for (var i = 0; i < s.length; i++) {
var t = s[i] + s[i + 1]
if (roman.indexOf(t) >= 0) {
res += num[roman.indexOf(t)]
i++
} else {
res += num[roman.indexOf(s[i])]
}
}
return res
};
14. 最长公共前缀
var longestCommonPrefix = function(strs) {
var res = ''
if (strs.length == 0) {
return res
}
for (var i = 0; i < strs[0].length; i++) {
for (var j = 0; j < strs.length; j++) {
if (strs[0][i] != '' && strs[0][i] != strs[j][i]) {
return res
}
}
res += strs[0][i]
}
return res
};
20. 有效的括号
var isValid = function(s) {
if (s.length % 2 !== 0) return false
let tmp = ['(', '[', '{', ')', ']', '}'] // 012345
let result = []
for (let i = 0; i < s.length; i++) {
if (tmp.indexOf(s[i]) <= 2) {
result.push(s[i])
} else {
let last = result.pop()
if (tmp.indexOf(last) + 3 != tmp.indexOf(s[i])) {
return false
}
}
}
if (result.length > 0) return false
return true
};
21. 合并两个有序链表
var mergeTwoLists = function(l1, l2) {
let prevhead = new ListNode(-1)
let prev = prevhead
while (l1 !== null && l2 !== null) {
if (l1.val <= l2.val) {
prev.next = l1
l1 = l1.next
} else {
prev.next = l2
l2 = l2.next
}
prev = prev.next
}
prev.next = l1 === null ? l2 : l1
return prevhead.next
};
26. 删除有序数组中的重复项
var removeDuplicates = function(nums) {
for (var i = 0; i < nums.length; i++) {
if (nums[i] == nums[i + 1]) {
nums.splice(i, 1);
i--
}
}
return nums.length
};
27. 移除元素
var removeElement = function(nums, val) {
for (let i = 0; i < nums.length; i++) {
if (nums[i] == val) {
nums.splice(i, 1);
i--;
}
}
return nums.length
};
35. 搜索插入位置
var searchInsert = function(nums, target) {
var min = 0;
var max = nums.length - 1;
if (target < nums[min]) return min;
if (target > nums[max]) return max + 1;
while (min <= max) {
var mid = parseInt((min + max) / 2)
if (target == nums[mid]) {
return mid
} else if (target > nums[mid]) {
min = mid + 1
} else {
max = mid - 1
}
}
return min
};
58. 最后一个单词的长度
var lengthOfLastWord = function(s) {
s = s.trim().replace(/\s+/g, ' ')
var arr = s.split(' ')
return arr[arr.length - 1].length
};