2019-10-13

####Binary Search

```

func search(nums []int, target int) int {

if len(nums) == 0 {

return -1

}

start, end := 0, len(nums)-1

for start <= end {

mid := (start + end) / 2

if nums[mid] == target {

return mid

}

if nums[mid] > target {

end = mid - 1

continue

}

if nums[mid] < target {

start = mid + 1

}

}

return -1

}

```

####Simplify Path

```

strings.FieldsFunc(path, func(s rune) bool {

if s == '/' {

return true

}

return false

})

for i := 0; i < len(dirs); i++ {

if dirs[i] == "." {

dirs = append(dirs[:i], dirs[i+1:]...)

i--

} else {

if dirs[i] == ".." {

if i == 0 {

dirs = dirs[1:]

i--

continue

}

dirs = append(dirs[:i-1], dirs[i+1:]...)

i -= 2

}

}

}

res := "/"

for i := 0; i < len(dirs); i++ {

res += dirs[i]

if i != len(dirs)-1 {

res += "/"

}

}

return res

}

```

####Search a 2D Matrix

```

func searchMatrix(matrix [][]int, target int) bool {

if len(matrix) == 0 || len(matrix[0]) == 0 {

return false

}

n := len(matrix)

m := len(matrix[0])

if target < matrix[0][0] || target > matrix[n-1][m-1] {

return false

}

var mid int

low, high := 0, n-1

for low <= high {

mid = (low + high) / 2

if matrix[mid][0] > target {

high = mid - 1

} else if matrix[mid][0] < target {

low = mid + 1

} else {

return true

}

}

left, right := 0, m-1

for left <= right {

mid = (left + right) / 2

if matrix[high][mid] > target {

right = mid - 1

} else if matrix[high][mid] < target {

left = mid + 1

} else {

return true

}

}

return false

}

```

####Full PermuteΩ

```

func permute(nums []int) [][]int {

var ret [][]int

l := len(nums)

if l == 0 {

return ret

}

helper(nums, 0, l-1, &ret)

return ret

}

func helper(nums []int, begin, end int, ret *[][]int) {

if begin == end {

t := make([]int, len(nums))

copy(t, nums) //这里一定要copy

*ret = append(*ret, t)

return

}

for i := begin; i <= end; i++ {

nums[begin], nums[i] = nums[i], nums[begin]

helper(nums, begin+1, end, ret)

nums[begin], nums[i] = nums[i], nums[begin]

}

}

```

你可能感兴趣的:(2019-10-13)