Java PriorityQueue/HEAP - 7 lines of code EASY


  • 0
    J
    public class Solution {
        public int arrayPairSum(int[] nums) {
            PriorityQueue<Integer> q = new PriorityQueue<Integer>(nums.length);
            for(int i = 0; i < nums.length; i++) q.add(nums[i]);
            //put them in a heap : 1,2,3,4
    
            int sum = 0;
            while(q.size() > 1) {
               //Count every other one, and throw one away
                sum += q.poll();
                q.poll();
            }
            return sum;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.