LeetCode-26 delete duplicates in ordered array

Insert picture description here
Here are two solutions

Speed ​​indicator (official excellent solution)

When I was writing this question, I didn’t read the question seriously. I didn’t see the condition of sorting, so I took a detour. If I noticed that the condition is still relatively simple,
i is a slow pointer, j is a fast pointer, and the array is because of the order. Permutation, set i=0 as the first element, if the second element j is not equal to i, then assign j to ++i elements, if they are the same, continue to traverse. Only add different elements when they appear.

 public static int removeDuplicates(int[] nums) {
    
    
	    if(nums.length==0)return 0;
	    int i=0;
	    for(int j=1;j<nums.length;j++){
    
    
	    	if(nums[i]!=nums[j]){
    
    
	    		nums[++i]=nums[j];
	    	}
	    }
	    return i+1;
    }

Hash table solution (general solution, not limited to sorted array)

This is my own solution to this problem, the running time is not the above block (3ms:1ms), but the memory consumption is smaller than that

Idea: The
hash table is empty at the beginning, and put unique key-value pairs in the hash table (the array element is the key, and the array subscript is the value. This is to facilitate the comparison of whether the key is duplicated)
Use containsKey to see if it is duplicated, use A size to mark the number of numbers, and then assign each non-repeated number in turn from nums[0], and at the same time put each number in the map for conditional judgment on the following numbers

public static int removeDuplicates(int[] nums) {
    
    
		int size=0;	//待返回的不重复元素个数
		Map<Integer, Integer>map=new HashMap<Integer, Integer>(); //将不重复的数组元素往map中放
		for (int i=0;i<nums.length;i++) {
    
    
			if(!map.containsKey(nums[i])){
    
    //同时用map的containsKey方法决定遍历元素是否在map中存在,从而决定是否往里边放
					nums[map.size()]=nums[i]; //将这个不重复的数紧接着赋值到上一个的后边
					map.put(nums[map.size()], i); //将这个数同时放到map中
					size++;//有效数的个数+1
			}
		}
	        return size;
	 }

Guess you like

Origin blog.csdn.net/WA_MC/article/details/115018376