美文网首页
数组算法相关题目--Swift

数组算法相关题目--Swift

作者: 派大星的博客 | 来源:发表于2018-11-01 11:34 被阅读2次

    1、提莫攻击

    class Solution {
        func findPoisonedDuration(_ timeSeries: [Int], _ duration: Int) -> Int {
            if timeSeries.count == 0 {
                return 0
            }
            var sum = 0
            var index = 0
            while index < timeSeries.count - 1 {
                let left = timeSeries[index]
                let right = timeSeries[index + 1]
                let min = (right - left) > duration ? duration : (right - left)
                sum += min
                index += 1
            }
            return sum + duration
        }
    }
    

    2、 非递减数组

    class Solution {
        func checkPossibility(_ nums: inout [Int]) -> Bool {
            var changeCount = 0
            for index in 0 ..< nums.count - 1 {
                if nums[index] > nums[index + 1] {
                    if index > 0 {
                        if (nums[index - 1] < nums[index + 1]){
                            nums[index] = nums[index + 1]
                        } else {
                            nums[index + 1] = nums[index]
                        }
                    }
                    changeCount += 1
                    if changeCount > 1 {
                        return false
                    }
                }
            }
            return true
        }
    }
    

    3、最长且连续的的递增序列

        func findLengthOfLCIS(_ nums: [Int]) -> Int {
            if nums.count > 1 {
                var result = 0
                var tmp = 0
                for index in 0 ..< nums.count {
                    tmp += 1
                    if index + 1 == nums.count {continue}
                    if nums[index] >= nums[index + 1] {
                        if tmp > result {
                            result = max(tmp, result)
                        }
                        tmp = 0
                    }
                }
                return max(result, tmp)
            }
            return nums.count
        }
    

    相关文章

      网友评论

          本文标题:数组算法相关题目--Swift

          本文链接:https://www.haomeiwen.com/subject/syntxqtx.html