0
点赞
收藏
分享

微信扫一扫

【Swift】LeedCode 汇总区间

小布_cvg 2022-02-09 阅读 151

【Swift】LeedCode 汇总区间
由于各大平台的算法题的解法很少有Swift的版本,小编这边将会出个专辑为手撕LeetCode算法题。新手撕算法。请包涵!!!

给定一个  无重复元素 的 有序 整数数组 nums 。

返回 恰好覆盖数组中所有数字 的 最小有序 区间范围列表 。也就是说,nums 的每个元素都恰好被某个区间范围所覆盖,并且不存在属于某个范围但不属于 nums 的数字 x 。

列表中的每个区间范围 [a,b] 应该按如下格式输出:

"a->b" ,如果 a != b
"a" ,如果 a == b
 

示例 1:

输入:nums = [0,1,2,4,5,7]
输出:["0->2","4->5","7"]
解释:区间范围是:
[0,2] --> "0->2"
[4,5] --> "4->5"
[7,7] --> "7"
示例 2:

输入:nums = [0,2,3,4,6,8,9]
输出:["0","2->4","6","8->9"]
解释:区间范围是:
[0,0] --> "0"
[2,4] --> "2->4"
[6,6] --> "6"
[8,9] --> "8->9"
 

提示:

0 <= nums.length <= 20
-231 <= nums[i] <= 231 - 1
nums 中的所有值都 互不相同
nums 按升序排列


Swift解法如下:

class Solution {
    func summaryRanges(_ nums: [Int]) -> [String] {
        var array:[String] = []
        var min = -1
        for index in 0..<nums.count{
          
            if index == nums.count - 1{
                if min == -1 {
                    array.append(String("\(nums[index])"))
               }else{
                    array.append(String("\(nums[min])->\(nums[index])"))   
               }
               break;
            }

            if nums[index] + 1 != nums[index + 1] {
               if min == -1 {
                    array.append(String("\(nums[index])"))
               }else{
                    array.append(String("\(nums[min])->\(nums[index])"))   
               }
                min = -1
            }else{
                if min == -1 {
                    min = index
                }
            }
        }
        return array
    }
}
举报

相关推荐

0 条评论