Java, using two Deque, easy to understand


  • 0
    D
    public class Solution {
        public String findContestMatch(int n) 
        {
            // input n is guaranteed make sense
            
            Deque<String> deq1 = new LinkedList<>();
            Deque<String> deq2 = new LinkedList<>();
            
            // enqueue to deq1 1 to n as string
            for (int i = 1; i <= n; i++) { deq1.addLast(String.valueOf(i)); }
            
            
            while (deq1.size() != 1 && deq2.size() != 1)
            {
                // combine items in deq1 and add into deq2
                while (!deq1.isEmpty() && deq1.size() != 1)
                {
                    deq2.addLast("(" + deq1.pollFirst() + "," + deq1.pollLast() + ")");
                }
                
                // combine items in deq2 and add into deq1
                while (!deq2.isEmpty() && deq2.size() != 1)
                {
                    deq1.addLast("(" + deq2.pollFirst() + "," + deq2.pollLast() + ")");
                }      
            }
            
            // one of these two deques contains the result string
            return deq1.size() == 1? deq1.pollFirst() : deq2.pollFirst();
        }
    }
    

Log in to reply
 

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