0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Java】Sorted Unique Array の連続範囲をまとめて返す(LeetCode: Summary Ranges)

Posted at

問題概要

以下の条件を満たす整数配列 nums が与えられる:
昇順にソート済み
要素はユニーク(重複なし)
このとき、配列の値を「連続している範囲」にまとめて、以下の形式の文字列リストで返す。

アプローチ

先頭から順に見ていき 連続しているか 判定
連続が途切れたタイミングで、区間を結果に追加
「区間の開始点」と「前回の値」を保持することで実現。

class Solution {
    public List<String> summaryRanges(int[] nums) {

        List<String> list = new ArrayList<>();

        if (nums.length == 0) return list;
        
        // 前回の値比較用
        int diff = 0;
        // listに格納する区間の開始点
        int temp = 0;

        for (int i = 0; i <= nums.length - 1; i++) {

            if (i == 0) {
                diff = nums[i];
                temp = nums[i];
                continue;
            }

            // 前回との差が1 → 連続
            if (nums[i] - 1 == diff) {
                diff = nums[i];
                continue;
            }

            // 前回の値が区間の開始点と同じ → 単一値
            if (nums[i - 1] == temp) {
                list.add(diff + "");
                temp = nums[i];
                diff = nums[i];
                continue;
            }

            // 連続でも単一値でもない → 区間として追加
            list.add(temp + "->" + nums[i - 1]);

            temp = nums[i];
            diff = nums[i];
        }

        // 最後の区間処理
        if (nums[nums.length - 1] == temp) {
            list.add(diff + "");
        } else {
            list.add(temp + "->" + nums[nums.length - 1]);
        }

        return list;
    }
}

補足(改善の余地)

処理自体は正しく動作するが、diff / temp の更新条件が多く少し複雑

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?