My code:
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<String> summaryRanges(int[] nums) {
if (nums == null)
return null;
List<String> sum = new ArrayList<String>();
if (nums.length == 0)
return sum;
else if (nums.length == 1) {
sum.add(Integer.toString(nums[0]));
return sum;
}
int begin = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i - 1] + 1) {
if (i == nums.length - 1) {
String s1 = Integer.toString(nums[begin]);
s1 += "->" + Integer.toString(nums[i]);
sum.add(s1);
}
continue;
}
else {
String s2 = Integer.toString(nums[begin]);
if (i - begin > 1)
s2 += "->" + Integer.toString(nums[i - 1]);
sum.add(s2);
begin = i;
if (begin == nums.length - 1) {
String s = Integer.toString(nums[begin]);
sum.add(s);
}
}
}
return sum;
}
public static void main (String[] args) {
Solution test = new Solution();
int[] nums = {0,1,2,4,5,7};
System.out.println(test.summaryRanges(nums));
}
}
My test result:
這次作業(yè)不難。也沒什么好總結(jié)的坯临。左手給我女朋友打電話秀又,她不接,右手敲著代碼系吩,敲著if語句。妒蔚。穿挨。所以說,真的不難肴盏。
**
總結(jié): Array
**
Anyway, Good luck, Richardo!
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<String> summaryRanges(int[] nums) {
ArrayList<String> ret = new ArrayList<String>();
if (nums == null || nums.length == 0)
return ret;
int headIndex = 0;
int tailIndex = 1;
while (tailIndex < nums.length) {
if (nums[tailIndex] - nums[tailIndex - 1] == 1) {
tailIndex++;
continue;
}
else {
String range = "";
if (tailIndex - 1 == headIndex)
range = String.valueOf(nums[headIndex]);
else
range = nums[headIndex] + "->" + nums[tailIndex - 1];
ret.add(range);
headIndex = tailIndex;
tailIndex++;
}
}
String range = "";
if (headIndex == nums.length - 1) {
range = String.valueOf(nums[headIndex]);
}
else {
range = nums[headIndex] + "->" + nums[tailIndex - 1];
}
ret.add(range);
return ret;
}
public static void main(String[] args) {
Solution test = new Solution();
int[] nums = {0, 1, 2, 4, 5, 6, 7};
System.out.println(test.summaryRanges(nums));
}
}
新寫的代碼科盛,感覺邏輯更加順暢些。不難菜皂。
Good luck, Richardo!
My Code:
public class Solution {
public List<String> summaryRanges(int[] nums) {
List<String> ret = new ArrayList<String>();
if (nums == null || nums.length == 0) {
return ret;
}
int prev = nums[0];
int next = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i - 1] + 1) {
next = nums[i];
}
else {
if (prev == next) {
ret.add("" + prev);
}
else {
ret.add("" + prev + "->" + next);
}
prev = nums[i];
next = nums[i];
}
}
if (prev == next) {
ret.add("" + prev);
}
else {
ret.add("" + prev + "->" + next);
}
return ret;
}
}
不知道為什么想出了這么簡潔巧妙的算法贞绵。
很美,很簡潔恍飘。
Anyway, Good luck, Richardo! -- 08/11/2016