zoukankan      html  css  js  c++  java
  • Daily Coding Problem: Problem #393

    class LargestRangeOfArray {
        /*
        * Given an array of integers, return the largest range, inclusive, of integers that are all included in the array.
        For example:
        * given the array [9, 6, 1, 3, 8, 10, 12, 11], return (8, 12) since 8, 9, 10, 11, and 12 are all in the array.
        * */
        fun largestRangeOfArray(array:IntArray):String{
            var left =0
            var right =0
            array.sort()
            var max = 0
            //1, 3, 6, 8, 9, 10, 11,12
            var size = array.size
            val result = HashMap<Int,ArrayList<Int>>()
            while (left<size){
                right = left+1
                if (right>=size-1){
                    right = size-1
                }
                val rangeArray = ArrayList<Int>()
                var maxLength = 0
                while (array[right]-array[left]==1){
                    rangeArray.add(array[left])
                    rangeArray.add(array[right])
                    left++
                    right++
                    maxLength++
                    if (right==size){
                        break
                    }
                }
                max = Math.max(max,maxLength)
                result.put(maxLength,rangeArray)
                //System.out.println("left:$left")
                left++
            }
           val resultList = result.get(max)
            resultList?.sort()
            return "(${resultList?.get(0)},${resultList?.get(resultList.size-1)})"
        }
    }
  • 相关阅读:
    最小的k个数
    复杂链表的复制
    二叉树中和为某一值的路径
    二叉搜索树的后序遍历序列
    STL之Deque容器
    STL之迭代器
    STL之Vector容器
    STL之string
    STL(标准模板库)基本概念
    文件I/O
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/12092464.html
Copyright © 2011-2022 走看看