LeetCode – 228. Summary Ranges

題目連結: https://leetcode.com/problems/summary-ranges/

參考解法:https://leetcode.com/problems/summary-ranges/discuss/63219/Accepted-JAVA-solution-easy-to-understand

法ㄧ:

    func summaryRanges(_ nums: [Int]) -> [String] {
   		var result: [String] = []
   		var i = 0
    	while i < nums.count {
    		let start = nums[i]
    		while (i+1) < nums.count && (nums[i+1] - nums[i]) == 1 {
    			i += 1
    		}
    		if nums[i] != start {
    			result.append("\(start)->\(nums[i])")
    		} else {
    			result.append("\(start)")
    		}
    		i += 1
    	}
    	return result
    }

法二:

    func summaryRanges(_ nums: [Int]) -> [String] {
        var result: [String] = []
        var start, end: Int?
        for i in 0 ..< nums.count {
        	if start == nil { start = nums[i] }
        	if end == nil && (i+1) < nums.count && (nums[i+1] - nums[i]) != 1 || i == (nums.count - 1) {
        		end = nums[i]
  				if start == end {
        			result.append("\(start!)")
        		} else {
        	    	result.append("\(start!)->\(nums[i])")
        		}
        		start = nil
        		end = nil
        	}
        }
        return result
    }