问题一
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 | func sumtotarget(nums []int, target int) []int { |
完美成功运行了,哈哈。想想这样不行啊 O(n^2)。然后仔细想了一下,可以利用 map 的特性来处理,就有下面这一段代码。
1 | func sumtotarget(nums []int, target int) []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 | func reverse(x int) int { |
问题三
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 | func isPalindrome(x int) bool { |