Find Missing Range

Given a sorted integer array nums, where the range of elements are in the inclusive range [lower, upper], return its missing ranges.

๋ฌธ์ œ๋ฅผ ์ •ํ™•ํ•˜๊ฒŒ ์ดํ•ดํ•˜๋Š” ๊ฒƒ์ด ์ค‘์š”ํ•˜๋‹ค! ๋ฌธ์ œ์—์„œ ๋ฌป๋Š” ๊ฒƒ์€ ์—†๋Š” ๋ฒ”์œ„์˜ ์ˆซ์ž๋“ค์„ ์ฐพ๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ ๊ทธ ๋ฒ”์œ„๋ฅผ ์ฐพ๋Š” ๊ฒƒ์ด๋‹ค! ์ฃผ์–ด์ง„ ์˜ˆ์‹œ๋ฅผ ํ†ตํ•ด ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์ปค๋ฒ„ํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ•˜๊ณ  ํ’€๊ธฐ!

Example 1 : Input : nums = [0,1,3,50,75], lower = 0 and upper = 99 Output : ["2", "4->49", "51->74", "76->99"]

Example 2 : Input : nums = [2,3,5,50,75], lower = 0 and upper = 99 Output : [0->1, 4, 6->49, 51->74, 76->99]

์•Œ๊ณ ๋ฆฌ์ฆ˜ 1. ๊ฒฝ์šฐ์˜ ์ˆ˜์— ๋”ฐ๋ผ ์ฝ”๋“œ๋ฅผ ์„ธ๋ถ„ํ™”ํ•œ๋‹ค. 2-1. lower < nums[i] : (lower+1, nums[i]-1) 2. nums[i] + 1 < nums[i+1} : (nums[i]+1,nums[i+1}-1) 3. nums[nums.length-1] < upper : (nums[nums.length-1]+1,upper)

์•Œ๊ณ ๋ฆฌ์ฆ˜์„ java๋กœ ๊ตฌํ˜„

package java_basic;

import java.util.*;
public class FindMissingRange {

	public static void main(String[] args) {
		int[] nums = {2,3,5,50,75};
		int lower=0, upper=99;
		System.out.println(solve(nums, lower, upper));
//		[0->1, 4, 6->49, 51->74, 76->99]
	}

	public static List<String> solve(int[] nums, int lower, int upper) {
		//0. ๊ทธ๋ฆ‡ ์ƒ์„ฑ
		List<String> result = new ArrayList<>();
		//1. ๊ธฐ์ €์‚ฌ๋ก€ ์ œ์™ธ 
		if(nums == null || nums.length == 0) {
			result.add(getRange(lower,upper));
			return result;
		}
		//2. case#1 
		if(lower < nums[0]) {
			result.add(getRange(lower, nums[0]-1));
		}
		// case#2
		for(int i=0; i< nums.length;i++) {
			if(nums[i] != nums[i+1] && nums[i]+1 < nums[i+1]) {
				result.add(getRange(nums[i]+1, nums[i+1]-1));
			}
		}
		// case#3
		if(nums[nums.length-1] < upper) {
			result.add(getRange(nums[nums.length-1]+1, upper));
		}
		return result;
	}

	public static String getRange(int lower, int upper) {
		return lower == upper ? String.valueOf(lower) : (lower+"->"+upper);
	}

}

Last updated