leetcode 简单题(一)

问题一

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解决

上来不由分说,先来一个 For 再说😄

1
2
3
4
5
6
7
8
9
10
11
12
func sumtotarget(nums []int, target int) []int {
l := len(nums)
for i, v := range nums {
r := target - v
for j:=i+1; j < l; j++ {
if r == nums[j] {
return []int{i, j}
}
}
}
return []int{}
}

完美成功运行了,哈哈。想想这样不行啊 O(n^2)。然后仔细想了一下,可以利用 map 的特性来处理,就有下面这一段代码。

1
2
3
4
5
6
7
8
9
10
11
12
func sumtotarget(nums []int, target int) []int {
numbers := make(map[int]int)
for i, v := range nums {
j, ok := numbers[v]
numbers[target - v] = i
if ok {
return []int{j, i}
}
}

return []int{}
}

第一刷,简单题都扛不住了。只能慢慢来了

问题二

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.

解决

注意的就是 int32 溢出的问题了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func reverse(x int) int {
var num int
for {
n := x % 10
if x == 0 && n == 0 {
break
}
x = x / 10
num = num * 10 + n
}
// -2147483648 到 2147483647
if num > math.MaxInt32 || num < math.MinInt32 {
return 0
}
return num
}

问题三

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.

解决

这道题数字回文,其实和上面的反转是一个道理,就是比较反转后的数字和实参是否相等就可以了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
func isPalindrome(x int) bool {
if x < 0 {
return false
}
var num int
cache := x
for {
n := x % 10

if x == 0 && n == 0 {
break
}
x = x / 10
num = num * 10 + n
}
if cache == num {
return true
}

return false
}