JAVA O(n) two pointers


  • 0
    O
    public class Solution {
        public boolean containsDuplicate(int[] nums) {
            HashSet<Integer> map = new HashSet<Integer>();
            int i = 0;
            int j = nums.length-1;
            while(i <= j){
                if(nums[i] != nums[j]){
                    if(map.contains(nums[j])){
                        return true;
                    }else{
                        map.add(nums[j]);
                    }
                    if(map.contains(nums[i])){
                        return true;
                    }else{
                        map.add(nums[i]);
                    }
                }else if(nums[i] == nums[j] && i != j){
                    return true;
                }else{
                   if(map.contains(nums[j])){
                        return true;
                    }else{
                        map.add(nums[j]);
                    } 
                }
                i++;
                j--;
            }
            return false;
        }
    }
    

Log in to reply
 

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