为了秋招,从今天开始每天至少在leetcode上刷五道题。同时为了加强go的学习,我准备后面做题先用go语言来做。由于今天是第一题,先做简单题就不写做题思路,直接写代码了。
func singleNumber(nums []int) int {
ans := nums[0]
for i := 1; i < len(nums); i++{
ans ^= nums[i]
}
return ans
}
func maxProfit(prices []int) int {
ans := 0
minVal := prices[0]
for i := 1; i < len(prices); i++{
ans = max(ans, prices[i] - minVal)
minVal = min(minVal, prices[i])
}
return ans
}
func min(a, b int)int{
if a < b{
return a
}else{
return b
}
}
func max(a, b int)int{
if a > b{
return a
}else{
return b
}
}
func climbStairs(n int) int {
if n == 1{
return 1
}else{
a, b := 1, 1
for i := 2; i <= n; i++{
a , b = b, a + b
}
return b
}
}
func maxSubArray(nums []int) int {
ans := nums[0]
for i := 1; i < len(nums); i++{
nums[i] = max(nums[i], nums[i] + nums[i - 1])
ans = max(ans, nums[i])
}
return ans
}
func isMatch(stack []byte, ch byte)bool{
i := len(stack) - 1
if((stack[i] == '{' && ch == '}' ) || (stack[i] == '[' && ch == ']') || (stack[i] == '(' && ch == ')')){
return true
}else{
return false
}
}
func isValid(s string) bool {
var stack []byte
for i := 0; i < len(s); i++{
if(len(stack) == 0 || !isMatch(stack, s[i])){
stack = append(stack, s[i])
}else{
stack = stack[:len(stack) - 1]
}
}
return len(stack) == 0
}
func quickSort(nums []int, begin int, end int){
if begin < end{
left, right := begin, end
key := nums[left]
for left < right{
for left < right && nums[right] >= key{
right--
}
nums[left] = nums[right]
for left < right && nums[left] <= key{
left++
}
nums[right] = nums[left]
}
nums[left] = key
quickSort(nums, begin, left - 1)
quickSort(nums, left + 1, end)
}
}
func twoSum(nums []int, target int) []int {
ump := make(map[int]int)
for i := 0; i < len(nums); i++{
_, ok := ump[target - nums[i]]
if ok{
return []int{i, ump[target - nums[i]]}
}else{
ump[nums[i]] = i;
}
}
return []int{-1,-1}
}
|