`

Missing Ranges

 
阅读更多
[分析]
此题若不考虑极大值极小值相关的corner case是简单的,如base version,当前leetcode的test case没有包含这些边缘case,因此是可以通过的。下面给出两种实现,base version和做了防溢出处理的robust version,并提供了相应的test case。
遇到整数数组问题,需要特别留意溢出问题,面试时可先写出base version然后再考虑增加放溢出处理,不然后者可能严重干扰主干思路,对我来说,添加上防溢出处理的时间远多于写出base version的时间。

public class MissingRanges {

    @Test
    public void testMissingRanges() {
        MissingRanges obj = new MissingRanges();
        List<String> expect = new ArrayList<String>();
        // case 1
        expect.add("-1->2147483646");
        int[] nums = {Integer.MAX_VALUE};
        List<String> actual1 = obj.findMissingRanges1(nums, -1, Integer.MAX_VALUE);
        List<String> actual2= obj.findMissingRanges2(nums, -1, Integer.MAX_VALUE);
        Assert.assertEquals(false, checker(expect, actual1));
        Assert.assertEquals(true, checker(expect, actual2));
        
        // case2
        expect.clear();
        int[] nums2 = {Integer.MAX_VALUE};
        List<String> actual3 = obj.findMissingRanges1(nums2, Integer.MAX_VALUE, Integer.MAX_VALUE);
        List<String>  actual4= obj.findMissingRanges2(nums2, Integer.MAX_VALUE, Integer.MAX_VALUE);
        Assert.assertEquals(false, checker(expect, actual3));
        Assert.assertEquals(true, checker(expect, actual4));
    }
    public boolean checker(List<String> expect, List<String> actual) {
        if (expect.size() != actual.size())
            return false;
        for (int i = 0; i < expect.size(); i++) {
            if (!expect.get(i).equals(actual.get(i)))
                return false;
        }
        return true;
    }
    // more robust version, take care of overflow edge case 
    public List<String> findMissingRanges2(int[] nums, int lower, int upper) {
        List<String> ret = new ArrayList<String>();
        if (nums == null)
            return ret;
        for (int i = 0; i < nums.length; i++) {
            if (lower < nums[i]) {
                if (lower < nums[i] - 1) {// avoid overflow
                    ret.add("" + lower + "->" + (nums[i] - 1));
                } else {
                    ret.add(String.valueOf(lower));
                }
            }
            if (nums[i] < Integer.MAX_VALUE) // avoid overflow
                lower = nums[i] + 1;
            else
                lower = Integer.MAX_VALUE;
        }
        // process lower==upper for case like: [-1], -1, 0
        // 添加nums[nums.length -1] != Integer.MAX_VALUE 这个判断,考虑case:
        // [Integer.MAX_VALUE], Integer.MAX_VALUE, Integer.MAX_VALUE
        if (lower < upper) {
            ret.add("" + lower + "->" + upper);
        } else if (lower == upper && !(nums.length > 0 && nums[nums.length -1] == Integer.MAX_VALUE))  {
            ret.add(String.valueOf(lower));
        }
        return ret;
    }
    
    // base version
    public List<String> findMissingRanges1(int[] nums, int lower, int upper) {
        List<String> ret = new ArrayList<String>();
        if (nums == null)
            return ret;
        for (int i = 0; i < nums.length; i++) {
            if (lower < nums[i]) {
                if (nums[i] - lower > 1) {
                    ret.add("" + lower + "->" + (nums[i] - 1));
                } else {
                    ret.add(String.valueOf(lower));
                }
            }
            lower = nums[i] + 1;
        }
        if (lower < upper) {
            ret.add("" + lower + "->" + upper);
        } else if (lower == upper) {
            ret.add(String.valueOf(lower));
        }
        return ret;
    }
}
分享到:
评论

相关推荐

    js-leetcode题解之163-missing-ranges.js

    javascript js_leetcode题解之163-missing-ranges.js

    python-leetcode题解之163-Missing-Ranges.py

    python python_leetcode题解之163_Missing_Ranges.py

    常见算法题答案及解析

    12. Missing Ranges:给定一个无序的整数数组,找出所有缺失的区间。 13. Longest Palindromic Substring:找出最长的回文子串,可以使用中心扩散法或者动态规划。 14. One Edit Distance:判断两个字符串是否相差一...

    Leetcode book刷题必备

    12. Missing Ranges:给定一个有序整数列表和两个端点值,找出缺失的范围。 13. Longest Palindromic Substring:找出字符串中的最长回文子串。 14. One Edit Distance:判断两个字符串是否只差一个字符操作。 15. ...

    LeetCode最全代码

    268| [Missing Number](https://leetcode.com/problems/missing-number/) | [C++](./C++/missing-number.cpp) [Python](./Python/missing-number.py) | _O(n)_ | _O(1)_ | Medium | LintCode || 318| [Maximum ...

    Cody‘s_Data_Cleaning_Techniques_Using_SAS_(Second_Edtion)

    - **Using DATA Step Approaches to Identify and Count Missing Values**: Discusses various DATA step techniques for identifying and counting missing values. - **Searching for a Specific Numeric Value**:...

    开源项目-studiofrenetic-period.zip

    开源项目-studiofrenetic-period.zip,Period provides a set of missing Time Range to Go, it cover all basic operations regardings time ranges.

    DXP2004 DRC 规则英文对照 pdf

    - **Bus ranges syntax errors** 总线范围的语法错误:如果在定义总线范围时使用了不正确的语法结构,则会产生这类错误。 - **Illegal bus range values** 非法的总线范围值:如果总线范围值不符合软件内部定义的...

    Kotlin - Kotlin Language Documentation 2.0.0

    If you encounter any issues or feel that something essential is missing from the documentation, consider contributing to the Kotlin project. The Kotlin community welcomes contributions, whether it’s ...

    Borland Delphi 2005 Architect Update 3

    to TStringFields results in access violation.5.00 of 5 Closed8785 Filter or Ranges on Nested Dataset&#39;s should restrict master as well.0.00 of 5 Closed8417 TCustomSQLDataSet.GetFieldData ...

    ABAP Program Tips

    - **RHSOBJCH – Fixes SPD Control Tables Missing in TXSWU3**:解决SPD控制表在TXSWU3中缺失的问题。 - **RV80HGEN**:生成RV80H表的示例程序。 - **Scheduling of System Maintenance Jobs**:系统维护任务的...

    CUDA11.0-C-Programming-Guide.pdf

    - The `satf` function, which saturates values to finite ranges, has been updated in the Warp matrix functions. This is useful for ensuring numerical stability in matrix computations. 17. **...

    ABAP_Program_Tips

    - **3.3.3 初始化日期范围在选择选项 (Initializing Date Ranges on Selection Options)** - **概述**:设置日期范围的选择选项,方便用户过滤数据。 - **用途**:提高报表的灵活性和可用性。 - **3.3.4 报表标题...

    SAP屠夫作品汇总

    7.4.1.1 Define Number Ranges for Actual Postings 501 7.4.1.2 Maintain Characteristic Groups 502 7.4.1.3 Assign Cha. Grp. for Assignment Screen 502 7.4.1.4 Assing Char. Grp. For Line Item Screen 503 ...

    CE中文版-启点CE过NP中文.exe

    There is apparently some malware going around that blocks execution of Cheat Engine (Saying file missing, check filename, etc...) If you have been a victim of this then try this windows repair tool to...

    曲线拟合工具CurveExpert 1.0

    ct. 18, 1995 v. 1.00 =========================================================================== + First release of CurveExpert 1.0. Oct. 26, 1995, v....==============================================...

    ABAP Program Tips.pdf

    2.2.1 RHSOBJCH – FIXES PD CONTROL TABLES MISSING IN TX SWU3.............................................11 3.8.12 CHECKING FOR BACKGROUND PROCESSING32 2.2.2 RV80HGEN.....................................

    JLink_Windows_V648.zip

    DLL: Infineon TLE98xx: Some J-Link LITEs could not connect establish a successful target connection due to missing firmware functionality. Fixed. DLL: JTAG: When only having 1 TAP in the JTAG chain ...

Global site tag (gtag.js) - Google Analytics