You are given a sorted unique integer array nums
.
Return the smallest sorted list of ranges that cover all the numbers in the array exactly. That is, each element of nums
is covered by exactly one of the ranges, and there is no integer x
such that x
is in one of the ranges but not in nums
.
Each range [a,b]
in the list should be output as:
"a->b"
ifa != b
"a"
ifa == b
Example 1:
Input: nums = [0,1,2,4,5,7]
Output: ["0->2","4->5","7"]
Approach
Java
import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class SummaryRanges {public static void main(String[] args) {int[] nums = { 0, 1, 2, 4, 5, 7 };List<String> res = summaryRanges(nums);System.out.println(Arrays.asList(res));}static List<String> summaryRanges(int[] nums) {int i = 0;int n = nums.length;int j = 0;List<String> res = new ArrayList<String>();while (i < n) {j = i;String str = "";str += nums[j];i++;while (i < n && (long) nums[i] - (long) nums[i - 1] == 1)i++;if (i > j + 1)str = (str + "->" + nums[i - 1]);res.add(str);}return res;}}
C++
#include <bits/stdc++.h>using namespace std;vector<string> summaryRanges(vector<int> &nums){long long int i = 0;long long int n = nums.size();long long int j = 0;vector<string> res;while (i < n){j = i;string str = "";str += to_string(nums[j]);i++;while (i < n && (long)nums[i] - (long)nums[i - 1] == 1)i++;if (i > j + 1)str = (str + "->" + to_string(nums[i - 1]));res.push_back(str);}return res;}int main(){vector<int> nums = {0, 1, 2, 4, 5, 7};vector<string> res = summaryRanges(nums);cout << "[";for (int i = 0; i < res.size() - 1; i++){cout << res[i] << ",";}cout << res[res.size() - 1] << "]";return 0;}
No comments:
Post a Comment