Given a sorted integer array that does not contain any duplicates, return a summary of the number ranges it contains.
Example
For nums = [-1, 0, 1, 2, 6, 7, 9], the output should be
solution(nums) = ["-1->2", "6->7", "9"].
Input/Output
[execution time limit] 3 seconds (java)
[memory limit] 1 GB
[input] array.integer nums
A sorted array of unique integers.
Guaranteed constraints:
0 ≤ nums.length ≤ 15,
(231 - 1) ≤ nums[i] ≤ 231 - 1.[output] array.string
String[] solution(int[] nums) {
if (nums.length == 0) return new String [0];
if (nums.length == 1) {
String [] result = { Integer.toString(nums[0]) };
return result;
}
int [] arr = new int [nums.length];
LinkedList <String> list = new LinkedList<>();
for (int i = 1; i < nums.length; i ++) {
// 1 차이가 날 때
if (nums[i] - nums[i - 1] == 1) {
// 현재 인덱스에 시작 인덱스 갱신
arr[i] = arr[i - 1];
// 마지막의 경우 가변 자료구조에 추가
if (i == nums.length - 1) list.add(summary(nums[arr[i]], nums[i]));
}
// 2 이상 차이 날 때
else {
// 이전 인덱스의 시작 인덱스가 이전 인덱스와 다를 때
if (arr[i - 1] != i - 1) list.add(summary(nums[arr[i - 1]], nums[i - 1]));
// 같을 때
else list.add(Integer.toString(nums[i - 1]));
// 마지막의 경우
if (i == nums.length - 1) list.add(Integer.toString(nums[i]));
// 현재 인덱스를 시작 인덱스로 갱신
arr[i] = i;
}
}
String [] result = new String [list.size()];
for (int i = 0; i < result.length; i ++) {
result[i] = list.get(i);
}
return result;
}
String summary (int a, int b) {
return a + "->" + b;
}