算法 - 数组1

121 阅读2分钟

算法 - 数组

基础知识学习

感受: 开始重新回顾算法,觉得二分查找肯定随便写,结果提笔忘字,脑袋僵住了。还是需要多多练习,多多思考。

题目1: 704. 二分查找

题目链接

文章讲解

视频讲解

题解

思考: 随想录提到了两个版本,左闭右开 和 左闭右闭 两个版本。 这种解释非常清楚,多看几遍练习一下就理解了。 个人感受理解之后 左闭右开的写法会比较顺手一些。

/*
 * @lc app=leetcode.cn id=704 lang=swift
 *
 * [704] 二分查找
 */

// @lc code=start
class Solution {
    func search(_ nums: [Int], _ target: Int) -> Int {
        var low = 0
        var high = nums.count
        while low < high {
            let mid = low + (high - low) / 2
            if nums[mid] == target {
                return mid
            } else if nums[mid] > target {
                high = mid
            } else {
                low = mid + 1
            }
        }
        return -1
    }
}
// @lc code=end


题目2: 27. 移除元素

题目链接

文章讲解

视频讲解

题解

思考:题解读了几遍,双指针法的确得结合图例来理解,否则脑袋循环很容易转晕。 当与目标值不等的时候 就是正常的赋值并后移。

如果相等的时候:fastIndex正常后移,slowIndex不动。

/*
 * @lc app=leetcode.cn id=27 lang=swift
 *
 * [27] 移除元素
 */

// @lc code=start
class Solution {
    func removeElement(_ nums: inout [Int], _ val: Int) -> Int {
        var slowIndex = 0
        for fastIndex in 0..<nums.count {
            if val != nums[fastIndex] {
                nums[slowIndex] = nums[fastIndex]
                slowIndex += 1
            }
        }
        return slowIndex
    }
}
// @lc code=end


题目2: 977. 有序数组的平方

题目链接

文章讲解

视频讲解

题解

思考:题解还是比较好理解的
双指针法的核心理念: 数组平方的最大值就在数组的两端,不是最左边就是最右边,不可能是中间

/*
 * @lc app=leetcode.cn id=977 lang=swift
 *
 * [977] 有序数组的平方
 */

// @lc code=start
class Solution {
    func sortedSquares(_ nums: [Int]) -> [Int] {
        var tail = nums.count - 1
        var res = nums
        var left = 0
        var right = tail
        while left <= right {
            if abs(nums[right]) > abs(nums[left]) {
                res[tail] = nums[right] * nums[right]
                tail -= 1
                right -= 1
            } else {
                res[tail] = nums[left] * nums[left]
                tail -= 1
                left += 1
            }
        }
        return res
    }
}
// @lc code=end