Java for LeetCode 163 Maximum Gap

來源:互聯網
上載者:User

標籤:

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.

Credits:
Special thanks to @porker2008 for adding this problem and creating all test cases.

解題思路:

由於要用到線性時間複雜度,比較排序已經不適用了(《演算法導論》P108),能夠用到的有 計數排序、基數排序、堆排序,由於計數排序比較適合小範圍的,基數排序最終會將順序排好,而我們不需要那麼複雜,因此,可以用桶排序,適當選擇桶之間的距離,保證最大的successive distance在兩桶之間即可,JAVA實現如下:

    public int maximumGap(int[] nums) {if (nums.length <= 1)return 0;int min = nums[0], max = nums[0];for (int num : nums) {min = Math.min(min, num);max = Math.max(max, num);}if (max == min)return 0;int distance = Math.max(1, (max - min) / (nums.length - 1));int bucket[][] = new int[(max - min) / distance + 1][2];for (int i = 0; i < bucket.length; i++) {bucket[i][0] = Integer.MAX_VALUE;bucket[i][1] = -1;}for (int num : nums) {int i = (num - min) / distance;bucket[i][0] = Math.min(num, bucket[i][0]);bucket[i][1] = Math.max(num, bucket[i][1]);}int maxDistance = 1, left = -1, right = -1;for (int i = 0; i < bucket.length; i++) {if (bucket[i][1] == -1)continue;if (right == -1) {right = bucket[i][1];continue;}left = bucket[i][0];maxDistance=Math.max(maxDistance, left-right);right=bucket[i][1];}return maxDistance;    }

 

Java for LeetCode 163 Maximum Gap

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.