How to efficiently remove duplicates from an array without using Set

后端 未结 30 2980
情深已故
情深已故 2020-11-22 07:29

I was asked to write my own implementation to remove duplicated values in an array. Here is what I have created. But after tests with 1,000,000 elements it took very long ti

30条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 07:54

    Here is my solution. The time complexity is o(n^2)

    public String removeDuplicates(char[] arr) {
            StringBuilder sb = new StringBuilder();
    
            if (arr == null)
                return null;
            int len = arr.length;
    
            if (arr.length < 2)
                return sb.append(arr[0]).toString();
    
            for (int i = 0; i < len; i++) {
    
                for (int j = i + 1; j < len; j++) {
                    if (arr[i] == arr[j]) {
                        arr[j] = 0;
    
                    }
                }
                if (arr[i] != 0)
                    sb.append(arr[i]);
            }
    
            return sb.toString().trim();
        }
    

提交回复
热议问题