0%

007. Reverse Integer

难度: Easy

刷题内容

原题连接

内容描述

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

 Input: 123
 Output: 321

Example 2:

 Input: -123
 Output: -321
 

Example 3:

 Input: 120
 Output: 21

Note:

 Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

解题方案

思路
**- 时间复杂度: O(1)**- 空间复杂度: O(N)**

思路:通过将数字转成数组,然后翻转再转回数字

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* @param {number} x
* @return {number}
*/
var reverse = function(x) {
var num = parseInt(x.toString().split('').reverse().join(''))
if(num > Math.pow(2, 31)) {
return 0
}
if(x < 0){
return num*(-1)
} else {
return num
}
};

008. String to Integer (atoi)

难度: Medium

刷题内容

原题连接

内容描述

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Implement atoi which converts a string to an integer.

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned.

Note:

Only the space character ' ' is considered as whitespace character.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.

Example 1:

1
2
Input: "42"
Output: 42

Example 2:

1
2
3
4
5
Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
Then take as many numerical digits as possible, which gets 42.

Example 3:

1
2
3
Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.

Example 4:

1
2
3
4
5
Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical
digit or a +/- sign. Therefore no valid conversion could be performed.

Example 5:

1
2
3
4
5
Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
Thefore INT_MIN (−231) is returned.

解题方案

思路 1
**- 时间复杂度: O(1)**- 空间复杂度: O(N)**

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* @param {string} str
* @return {number}
*/
var myAtoi = function(str) {
const INT_MAX = 2 ** 31 - 1;
const INT_MIN = -(2 ** 31);
str = str.match(/^\s*([-+]?\d+)/);
let strNum = str ? Number(str[0]) : 0;
if(strNum < INT_MIN ){
return INT_MIN
}else if(strNum > INT_MAX){
return INT_MAX
}else{
return strNum
}
};

9. Palindrome Number

难度: Easy

刷题内容

原题连接

内容描述

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.

Example 1:

Input: 121
Output: true
Example 2:

Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:

Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:

Coud you solve it without converting the integer to a string?

解题方案

思路 1
**- 时间复杂度: O(log2 N)**- 空间复杂度: O(1)**

  • 不使用字符串,使用除法分别从首尾获得数字,最后对比是否相同

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* @param {number} x
* @return {boolean}
*/
var isPalindrome = function(x) {
if(x<0||x!==0&&x%10===0)
return false;
var reverse = 0;
while (x>reverse){
reverse = reverse*10 +x%10;
x = Math.floor(x/10);
}
return reverse === x||Math.floor(reverse/10) === x;
};

思路 2
**- 时间复杂度: O(N)**- 空间复杂度: O(N)**

  • 转化为字符串,reverse字符串

代码:

1
2
3
var isPalindrome = function(x) {
return x.toString().split('').reverse().join('')==x.toString()?true:false;
};

11. Container With Most Water

难度: Medium

刷题内容

原题连接

内容描述

1
2
3
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.

Note: You may not slant the container and n is at least 2.

img

1
The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
1
2
3
4
Example:

Input: [1,8,6,2,5,4,8,3,7]
Output: 49

解题方案

对撞指针
**- 时间复杂度: O(N)**- 空间复杂度: O(1)**

  • 从数组两层对向查找,直到找到最大乘积

代码:

1
2
3
4
5
6
7
8
9
10
11
12
var maxArea = function (list) {
let i = 0,j = list.length -1,result = 0;
while(i < j){
result = Math.max(result ,(j - i ) * Math.min(list[i],list[j]))
if(list[i] < list[j]){
i++;
}else{
j--;
}
}
return result;
};

暴力解法
**- 时间复杂度: O(N²)**- 空间复杂度: O(1)**

代码

1
2
3
4
5
6
7
8
9
10
11
var maxArea = function (list) {
let result = 0;
for(let i = 0,len = list.length; i<len; i++){
for(let j = i+1; j<len; j++){
let x = (j - i);
let y = Math.min(list[i],list[j]);
result = Math.max(result,x*y)
}
}
return result;
};

12. Integer to Roman

难度: Medium

刷题内容

原题连接

内容描述

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

1
2
3
4
5
6
7
8
Symbol       Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

For example, two is written as II in Roman numeral, just two one’s added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9.
  • X can be placed before L (50) and C (100) to make 40 and 90.
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.

Example 1:
1
2
Input: 3
Output: "III"
Example 2:
1
2
Input: 4
Output: "IV"
Example 3:
1
2
Input: 9
Output: "IX"
Example 4:
1
2
3
Input: 58
Output: "LVIII"
Explanation: L = 50, V = 5, III = 3.
Example 5:
1
2
3
Input: 1994
Output: "MCMXCIV"
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

解题方案

**- 时间复杂度: O(N)**- 空间复杂度: O(1)**

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
let getMap = function () {
return {
1:'I',
4:'IV',
5:'V',
9:'IX',
10:'X',
40:'XL',
50:'L',
90:'XC',
100:'C',
400:'CD',
500:'D',
900:'CM',
1000:'M'
};
};

let match = function (result,num) {
let obj = getMap();
while (result.num >= num){
let n = parseInt(result.num /num);
result.num = result.num % num;
result.str = result.str + obj[num].repeat(n);
}
};

/**
* @param {number} num
* @return {string}
*/
var intToRoman = function (num) {
if(num < 1 || num > 3999) throw Error('error');
let obj = getMap();
if(num in obj) return obj[num];
let result = {
str:'',
num
};
match(result,1000);
match(result,900);
match(result,500);
match(result,400);
match(result,100);
match(result,90);
match(result,50);
match(result,40);
match(result,10);
match(result,9);
match(result,5);
match(result,4);
match(result,1);

return result.str;
};

13. Roman to Integer

难度: Easy

刷题内容

原题连接

内容描述

Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.

1
2
3
4
5
6
7
8
Symbol       Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

For example, two is written as II in Roman numeral, just two one’s added together. Twelve is written as, XII, which is simply X + II. The number twenty seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9.
  • X can be placed before L (50) and C (100) to make 40 and 90.
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

Example 1:
1
2
Input: "III"
Output: 3
Example 2:
1
2
Input: "IV"
Output: 4
Example 3:
1
2
Input: "IX"
Output: 9
Example 4:
1
2
3
Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:
1
2
3
Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.

解题方案

**- 时间复杂度: O(N)**- 空间复杂度: O(1)**

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* @param {string} roman
* @return {number}
*/
let romanToInt = function (roman) {
let result = 0;
let obj = {
'I':1,
'IV':4,
'V':5,
'IX':9,
'X':10,
'XL':40,
'L':50,
'XC':90,
'C':100,
'CD':400,
'D':500,
'CM':900,
'M':1000
};
for(let len = roman.length,i = len -1;i>=0; i--){
if(i - 1 >= 0 && `${roman.charAt(i - 1)}${roman.charAt(i)}` in obj){
result = result + obj[`${roman.charAt(i - 1)}${roman.charAt(i)}`];
i--;
}else{
result = result + obj[roman.charAt(i)];
}
}
return result;
};

014. Longest Common Prefix

难度: Easy

刷题内容

原题连接

内容描述

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

1
2
Input: ["flower","flow","flight"]
Output: "fl"

Example 2:

1
2
3
Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:

All given inputs are in lowercase letters a-z.

解题方案

思路
**- 时间复杂度: O(N)**- 空间复杂度: O(N)**

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* @param {string[]} strs
* @return {string}
*/
let longestCommonPrefix = function(strs) {
let firstStr = strs[0];
let result ='';
if(!strs.length){
return result;
}
for (let i = 0; i < firstStr.length; i++) {
for (let j = 1; j < strs.length; j++) {
if(firstStr.charAt(i) !== strs[j].charAt(i)){
return result;
}
}
result = result + firstStr.charAt(i);
}
return result;

};

015. 3Sum

难度: Medium

刷题内容

原题连接

内容描述

Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.

Note:

 The solution set must not contain duplicate triplets.

Example:

 Given array nums = [-1, 0, 1, 2, -1, -4],
 
 A solution set is:
 [
   [-1, 0, 1],
   [-1, -1, 2]
 ]

解题方案

思路
**- 时间复杂度: O(N²)**- 空间复杂度: O(N)**

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* @param {number[]} nums
* @return {number[][]}
*/
let threeSum = function(nums, n = 0) {
let result = [];
let len = nums.length;
if(!len) return result;
// 对数组进行排序
nums.sort((a,b)=>a-b);
for(let k = 0; k<len; k++){
//重复的元素则结果也一样,所以跳过该循环
if(k>0 && nums[k-1] === nums[k]){
continue;
}
let target = n - nums[k];
let i = k + 1;
let j = len -1;
while(i<j){
if(nums[i] + nums[j] === target){
result.push([nums[k],nums[i],nums[j]]);
while (i<j && nums[i] === nums[i+1]) i++;
while (i<j && nums[j] === nums[j-1]) j--;
i++;
j--;
}else if(nums[i] + nums[j] > target){
j--;
}else{
i++
}
}
}
return result;
};

016. 3Sum Closest

难度: Medium

刷题内容

原题连接

内容描述

Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.

Example:

 Given array nums = [-1, 2, 1, -4], and target = 1.
 
 The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

解题方案

思路
**- 时间复杂度: O(N²)**- 空间复杂度: O(N)**

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* @param {number[]} nums
* @param {number} target
* @return {number}
*/
var threeSumClosest = function(nums, target) {
let result = Infinity;
let len = nums.length;
if(len <= 3){
return nums.reduce((a,b)=>a+b,0);
}
nums.sort((a,b)=>a-b);
for(let k = 0; k<len-2; k++){
if(k>0 && nums[k-1] === nums[k]){
continue;
}
let i = k + 1;
let j = len -1;
while(i<j){
let count = nums[k] + nums[i] + nums[j];
if(count === target){
return target;
}
if(Math.abs(result - target) > Math.abs(count - target)){
result = count;
}
if(count > target){
j--
}else{
i ++
}
}
}
return result;
};

017. Letter Combinations of a Phone Number

难度: Medium

刷题内容

原题连接

内容描述

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.

img

Example:

 Input: "23"
 Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
 

Note:

Although the above answer is in lexicographical order, your answer could be in any order you want.

解题方案

递归版本
**- 时间复杂度: O(N²)**- 空间复杂度: O(N)**

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* 递归函数
* @param digits 传入的数字
* @param index 当前是第几个数字
* @param str 当前已拼装的字符串
* @param list 结果集
*/
let helper = function (digits, index, str, list) {
let map = {
2: 'abc',
3: 'def',
4: 'ghi',
5: 'jkl',
6: 'mno',
7: 'pqrs',
8: 'tuv',
9: 'wxyz'
};
if (str.length === digits.length) {
list.push(str);
return false;
}
let strs = map[digits[index]];
for (let i = 0; i < strs.length; i++) {
helper(digits, index + 1, str + strs.charAt(i), list)
}
};
let letterCombinations = function (digits) {
let list = [];
if (digits) {
helper(digits, 0, '', list);
}
return list;
};

非递归版本
**- 时间复杂度: O(N²)**- 空间复杂度: O(N)**

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* @param {string} digits
* @return {string[]}
*/
let letterCombinations = function (digits) {
let map = {
2: 'abc',
3: 'def',
4: 'ghi',
5: 'jkl',
6: 'mno',
7: 'pqrs',
8: 'tuv',
9: 'wxyz'
};
let res = [];
for(let i = 0,len = digits.length; i<len; i++){
let str = map[digits.charAt(i)];
if(!res.length){
for(let i = 0,len = str.length; i<len; i++){
res.push(str.charAt(i));
}
}else{
let r = [];
for(let j = 0,length = res.length; j<length; j++){
for(let i = 0,len = str.length; i<len; i++){
r.push(res[j] + str.charAt(i));
}
}
res = r;
}
}
return res;
};