代码随想录算法训练营|day1

第一章 数组

  • 704.二分查找
  • 27.移除元素
  • 相关推荐:

704.二分查找

文章详解
(1)左闭右闭

func search(nums []int, target int) int {
	left := 0
	right := len(nums) - 1
	for left <= right {
		mid := left + (right-left) >> 2
		if target == nums[mid] {
			return mid
		} else if target < nums[mid]  {
			right = mid - 1
		} else if target > nums[mid] {
			left = mid + 1
		}
	}
	return -1
}

(2)左闭右开

func search(nums []int, target int) int {
	left := 0
	right := len(nums)
	for left < right {
		mid := left + (right-left) >> 2
		if target == nums[mid] {
			return mid
		} else if target < nums[mid]  {
			right = mid 
		} else if target > nums[mid] {
			left = mid + 1
		}
	}
	return -1
}

27.移除元素

数组中的元素在内存中地址连续,只能覆盖,不能删除
文章详解
(1)暴力解法:外循环遍历数组,内循环更新数组

func removeElement(nums []int, val int) int {
    n := len(nums)
    for i := 0; i < n; i++ {
        if val == nums[i] {
            for j := i + 1; j < n; j++ {
                nums[j - 1] = nums[j]
            }
            i--
            n--
        }
    }
    return n
}

(2)快慢指针:

func removeElement(nums []int, val int) int {
    slow := 0
    n := len(nums)
    for fast := 0; fast < n; fast++ {
        if val != nums[fast] {
            nums[slow] = nums[fast]
            slow++
        }
    }
    return slow
}

(3)相向指针:

func removeElement(nums []int, val int) int {
    left := 0
    right := len(nums) - 1
    for left <= right {
        if val == nums[left] {
            nums[left] = nums[right]
            right--
        }else {
            left++
        }
    }
    return left
}

相关推荐:

26. 删除有序数组中的重复项
(1)暴力解法

func removeDuplicates(nums []int) int {
    n := len(nums)
    if n == 0 {
        return 0
    }
    for i := 1; i < n; i++ {
        if nums[i - 1] == nums[i] {
            for j := i + 1; j < n; j++{
                nums[j - 1] = nums[j]
            }
            i--
            n--
        }
    }
    return n
}

(2)快慢指针

func removeDuplicates(nums []int) int {
   n := len(nums)
   if n == 0 {
       return 0
   }
   slow := 1
   for fast := 1 ; fast < n; fast++ {
       if nums[fast - 1] != nums[fast]{
           nums[slow] = nums[fast]
           slow++
       }
   }
   return slow
}

283. 移动零
844. 比较含退格的字符串
977. 有序数组的平方

你可能感兴趣的:(代码随想录练习,go)