Use of HashSet collection

Set and map collections are rarely used before. Here, when I meet when writing the question, I will summarize the usage (Map will meet again next time):

Topic:
Given two arrays, write a function to calculate their intersection.

Example 1:

Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
Example 2:

Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]

Description:

Each element in the output result must be unique.
We can ignore the order of output results.

	//上面说过输出的每个元素都是唯一的,那么就是说即使交集重复的也只会输出一个
	//换句话说就可以去重判断是否存在即可
	//去重的话可以用到set集合,它内部的 元素都是无序并且不重复,添加的元素如果是重复的则会返回false
	//因为不允许有重复 元素,所以内部也提供了判断集合里是否存在该元素的方法contains()
    public static int[] intersection(int[] nums1, int[] nums2) {
    
    
    	HashSet<Integer> s1=new HashSet<Integer>();
    	HashSet<Integer> s2=new HashSet<Integer>();
    	for(int num:nums1) {
    
    
    		s1.add(num);
    	}
    	for(int num:nums2) {
    
    
    		s2.add(num);
    	}
    	HashSet<Integer> temp=new HashSet<Integer>();
    	if(s1.size()<s2.size()) {
    
    
    		for(int num:s1) {
    
    
    			if(s2.contains(num)) {
    
    
    				temp.add(num);
    			}
    		}
    	}else {
    
    
    		for(int num:s2) {
    
    
    			if(s1.contains(num)) {
    
    
    				temp.add(num);
    			}
    		}
    	}
    	int []arr=new int[temp.size()];
    	int i=0;
    	//这里注意set集合里的遍历是没有顺序的,不能保证顺序,并且set集合不支持索引访问
    	//如果需要索引的话,需要返回set集合的迭代器
    	//遍历里面的元素简单直接的就是通过增强for循环直接获取
    	for(int num:temp) {
    
    
    		arr[i++]=num;
    	}
    	return arr;
    }

Summarizing the usage: There are also some written comments in the above question explanation. The elements in the Set collection have no duplicates. You can use it when you encounter the deletion of duplicates later, at the expense of space in exchange for time, so its search is very efficient. There is no guarantee that the stored elements are in order, and index access is not supported, so when traversing this collection, you can use the enhanced for loop method, or return the iterator of the collection (there will be methods below)

Common methods of HashSet (most of the return values ​​are Boolean values, because duplicate values ​​are not allowed, so it will be judged before the operation, and if there are duplicate values, it will return false):

add(E): return false if there are duplicate elements
clear(): empty
containg(Object): determine whether the specified element is included
iterator(): return the iterator of this collection
size()
remove(): delete if there is

Guess you like

Origin blog.csdn.net/qq_50646256/article/details/113578337