● 242.有效的字母异位词
func isAnagram(s string, t string) bool {
length := len(s)
if(length != len(t)){
return false
}
smap,tmap := make(map[byte]int),make(map[byte]int)
for i:=0 ; i < length ; i++{
smap[s[i]]++
tmap[t[i]]++
}
for i:=0 ; i < len(s) ; i++{
if(smap[s[i]] != tmap[s[i]]){
return false
}
}
return true
}
● 349. 两个数组的交集
func intersection(nums1 []int, nums2 []int) []int {
a := make(map[int]int)
for _,v := range nums1{
a[v]++
}
var res []int
for i := 0; i < len(nums2); i++{
b := nums2[i]
if(a[b] != 0){
res = append(res,b)
a[b] = 0
}
}
return res
}
● 202. 快乐数
func isHappy(n int) bool {
count := make(map[int]int)
for{
newNum := newNum(n)
if(newNum == 1){
return true
}
if(count[newNum] == 0){
count[newNum]++
}else{
return false
}
n = newNum
}
return true
}
func newNum(n int) int{
var res []int
sum := 0
for n!=0{
a := n % 10
res = append(res,a)
n = n / 10
}
for _,v := range res{
sum = sum + v * v
}
return sum
}
1. 两数之和
func twoSum(nums []int, target int) []int {
a := make(map[int]int)
for k,v := range nums{
a[v] = k + 1
}
for i:=0 ; i<len(nums) ; i++{
b := target-nums[i]
if(a[b] != 0 && i != a[b]-1){
return []int{i,a[b]-1}
}
}
return nil
}
总结:以后还是要仔细读题…