【leetcode】 Maximum Gap

来源:互联网 发布:萧山网络问政南阳 编辑:程序博客网 时间:2024/05/21 00:01

问题描述:

Given an unsorted array, find the maximum difference between the successive elements in its sorted form.Try to solve it in linear time/space.Return 0 if the array contains less than 2 elements.You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range.

问题分析:

用桶排序或者基数排序都可以解决。详细算法见:http://blog.csdn.net/gqqnb/article/details/42142639

 public int maximumGap(int[] num) { if(num.length<2) return 0; int max=num[0]; int min=num[0]; for(int i:num){ min=Math.min(i, min); max=Math.max(i, max); } int gap  = (int)Math.ceil((double)(max - min)/(num.length - 1)); int n = (max-min)/gap+1; int[] minList = new int[n]; int[] maxList = new int[n]; List[] list = new ArrayList[n]; for(int i=0;i<n;i++){ list[i]=new ArrayList(); } //遍历 for(int i=0;i<num.length;i++){ if(list[(num[i]-min)/gap].size()==0){ minList[(num[i]-min)/gap]=num[i]; maxList[(num[i]-min)/gap]=num[i];// System.out.println("min1"+minList[(num[i]-min)/num.length]); }else{ minList[(num[i]-min)/gap]=minList[(num[i]-min)/gap]>num[i]?num[i]:minList[(num[i]-min)/gap]; maxList[(num[i]-min)/gap]=maxList[(num[i]-min)/gap]>num[i]?maxList[(num[i]-min)/gap]:num[i];// System.out.println("min"+minList[(num[i]-min)/num.length]); } list[(num[i]-min)/gap].add(num[i]); } //开始遍历条件数组 int previous=Integer.MIN_VALUE; int temp=0; List resultList = new ArrayList(); for(int i=0;i<n;i++){// System.out.println("list "+i+" size is "+list[i].size());if(list[i].size()==0){continue;}else{temp=maxList[i]-minList[i];//System.out.println(" temp is "+temp+" minList["+i+"] "+minList[i]);resultList.add(temp>(minList[i]-previous)?temp:(minList[i]-previous));previous=maxList[i];} } int answer = (int) resultList.get(0);// System.out.println(answer); for(int i=0;i<resultList.size();i++) answer=(int) (answer<((Integer)resultList.get(i))?(Integer)resultList.get(i):answer); return answer; }


0 0
原创粉丝点击