228. Summary Ranges

哇呀呀..生氣啦~發表於2019-06-20


June-19-2019

這個題居然也沒記過,可能當時覺得太簡單了。

楞做法

    public List<String> summaryRanges(int[] nums) {
        List<String> result = new ArrayList<>();
        if (nums.length == 0) return result;
        
        StringBuilder sb = new StringBuilder();
        int prev = nums[0];
        sb.append(prev);
        for (int i = 1; i < nums.length; i ++) {
            int temp = nums[i];
            if (temp == prev + 1) {
                prev = temp;
            } else {
                if (prev != Integer.valueOf(sb.toString())) {
                    sb.append("->").append(prev);
                }
                result.add(sb.toString());
                sb = new StringBuilder();
                sb.append(temp);
                prev = temp;
            }
        }
        
        if (prev != Integer.valueOf(sb.toString())) {
                sb.append("->").append(prev);
        }
        result.add(sb.toString());
        return result; 
    }

然後另一種是通過nums[r] - nums[l] == r - l 來迅速完成l->r
缺點是在[1,3,5,7,9,11]這種每次R都要從最右邊到最左邊,反而變成O(n²)了

    public List<String> summaryRanges(int[] nums) {
        List<String> result = new ArrayList<>();
        if (nums.length == 0) return result;
        
        int r = nums.length - 1;
        for (int l = 0; l < nums.length; l ++) {
            while (l <= r) {
                if (nums[l] == nums[r]) {
                    result.add(new StringBuilder(Integer.toString(nums[l])).toString());
                    r = nums.length - 1;
                    break;
                } else if (nums[r] - nums[l] == r - l) {
                    result.add(new StringBuilder(Integer.toString(nums[l]))
                                                            .append("->")
                                                            .append(nums[r])
                                                            .toString());
                    l = r;
                    r = nums.length - 1;
                    break;
                } else {
                    r --;
                }
            }
        }

        return result;
    }

其實可以二分,類似於歸併排序的辦法,缺點是merge 時候麻煩點,得處理[1-3][4-5]和[3][4]這種情況= =然後我有點懶就沒寫。

相關文章