Interview Question - minimum length to sort array

这是网上看到的一道面经题目,觉得很有意思。总结下。

题目:
给你一个未排序的数组,问最短从这个数组的那一段开始排序即能让整个数组有序
比如(1,2,5,7,6,4,9),那么从 (5,7,6,4)这一段排序就足够了
最坏情况O(N^2),最优情况O(N)时间O(1)空间

My code:

public int getMinLength(int[] nums) {
    if (nums == null || nums.length == 0) {
        return 0;
    }
    
    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;
    
    for (int i = 1; i < nums.length; i++) {
        if (nums[i] > nums[i - 1]) {
            continue;
        }
        else {
            min = Math.min(min, nums[i]);
            max = Math.max(max, nums[i - 1]);
        }
    }
    
    if (max == Integer.MIN_VALUE) {
        return 0;
    }
    
    int begin = 0;
    int end = nums.length - 1;
    while (nums[begin] < min) {
        begin++;
    }
    
    while (nums[end] > max) {
        end--;
    }
    
    System.out.println("We should sort: [" + begin + ", " + end + "]");
    return end - begin + 1;
}

自己参考了答案才写出来。

reference:
http://stackoverflow.com/questions/15855594/min-n-m-so-that-whole-array-will-be-sorted/15855670#15855670

Anyway, Good luck, Richardo! -- 09/13/2016

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容