funccontainsDuplicate(nums []int)bool { mp := make(map[int]bool) for _, n := range nums { _, ok := mp[n] if ok { returntrue }else { mp[n]=true } } returnfalse }
funcmaxSubArray(nums []int)int { maxNum := -1000000 sum := -1000000 for _, n := range nums { if sum < 0 { sum = n }else { sum += n } if sum > maxNum { maxNum = sum } } if maxNum == -1000000 { return0 }else { return maxNum } }
functwoSum1(nums []int, target int) []int { var res []int = make([]int,2) for i:=0; i < len(nums); i++ { for j := i + 1; j < len(nums); j++ { if nums[i] + nums[j] == target { res[0] = i res[1] = j return res } } } return res }
更简单的方式,复杂度小于平方
1 2 3 4 5 6 7 8 9 10
functwoSum(nums []int, target int) []int { var numsMap = make(map[int]int) for i, n := range nums{ if k, ok := numsMap[target - n]; ok { return []int{k, i} } numsMap[nums[i]] = i } returnnil }
funcmaxNum(x, y int)int { if x > y { return x } return y }
funcminNum(x, y int)int { if x > y { return y } return x }
funcmaxProfit(prices []int)int { iflen(prices) <= 1 { return0 } min := prices[0] max := 0 for i := 1; i < len(prices); i++ { max = maxNum(max, prices[i]-min) min = minNum(min, prices[i]) } return max }