Is that cheating?!


  • 0
    T

    I am saving a previously deleted value. Since the test cases contained cases where the elements are -1, Integer.Min Integer.Max, I decided to use Random as an initial value for my variable. It seems like it is cheating! Is it? Moreover, it seems like at the end of the method I am duplicating a logic. Is there a way to eliminate that?

        public ListNode deleteDuplicates(ListNode head) {
            if(head == null || head.next == null) return head;
            
            ListNode prev = new ListNode(-1), i = head;
            prev.next = i;
            int prevDeletedVal = new Random().nextInt();
            ListNode returnHead = prev;
            
            while(i!= null && i.next != null){
                if(i.val == i.next.val) {
                    i.next = i.next.next;
                    prevDeletedVal = i.val;
                }
                else if(i.val == prevDeletedVal){
                    prev.next = prev.next.next;
                    i = prev.next;
                }
                else{
                    prev = prev.next;
                    i = prev.next;
                }   
            }
            
            if(i.val == prevDeletedVal){
                prev.next = prev.next.next;
                i = prev.next;
            }
            
            return returnHead.next;
        }
    

Log in to reply
 

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