[GeeksForGeeks] Find the largest pair sum in an unsorted array

本文介绍了三种算法来解决寻找未排序数组中最大的两个元素之和的问题。第一种使用排序,复杂度为O(n*logn);第二种利用堆,实现O(n)时间复杂度;第三种扫描数组一次更新最大及次大的值,同样达到O(n)复杂度。

Given an unsorted array, find the largest pair sum.

 

Solution 1. O(n*logn) runtime, using sorting

 

Solution 2. O(n) runtime, using heapify (max priority queue)

Option 1. Use Java priority queue API, easy to implement but uses O(n) extra memory.

Option 2.  Since we are given an array, heapify the array to a max pq. This does not use extra memory.

Heapify takes O(n) runtime;

delete the max value from the heapified array takes O(logn) runtime as we need to percolate down the 

new head element.

 1 public class Solution {
 2     public int findLargestPair(int[] A){
 3         if(A == null || A.length <= 1){
 4             return Integer.MIN_VALUE;
 5         }
 6         heapify(A);
 7         int firstMax = A[0], secondMax = 0;
 8         A[0] = A[A.length - 1];
 9         percolateDown(A, A.length - 1, 0);
10         secondMax = A[0];
11         return firstMax + secondMax;
12     }
13     private void heapify(int[] A){
14         for(int i = A.length / 2 - 1; i >= 0; i--){
15             percolateDown(A, A.length, i);
16         }
17     }
18     private void percolateDown(int[] A, int len, int idx){
19         int maxIdx = idx;
20         int leftChildIdx = 2 * idx + 1;
21         int rightChildIdx = 2 * idx + 2;
22         if(leftChildIdx < len && A[leftChildIdx] > A[maxIdx]){
23             maxIdx = leftChildIdx;
24         }
25         if(rightChildIdx < len && A[rightChildIdx] > A[maxIdx]){
26             maxIdx = rightChildIdx;
27         }
28         if(maxIdx != idx){
29             int temp = A[idx];
30             A[idx] = A[maxIdx];
31             A[maxIdx] = temp;
32             percolateDown(A, len, maxIdx);
33         }
34     }
35 }

 

Solution 3. O(n) runtime, O(1) space, scan the input array once and upate the largest and second largest values along the way.

 1 public int findLargestPair(int[] A){
 2     if(A == null || A.length <= 1){
 3         return Integer.MIN_VALUE;
 4     }
 5     int firstMax = Math.max(A[0], A[1]);
 6     int secondMax = Math.min(A[0], A[1]);
 7     for(int i = 2; i < A.length; i++){
 8         if(A[i] >= firstMax){
 9             secondMax = firstMax;
10             firstMax = A[i];
11         }
12         else if(A[i] > secondMax){
13             secondMax = A[i];
14         }
15     }
16     return firstMax + secondMax;
17 }

 

转载于:https://www.cnblogs.com/lz87/p/7220208.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值