Home > Java > Javagetting Started > body text

How to find numbers that appear only once in an integer array

王林
Release: 2020-09-07 17:50:13
forward
2603 people have browsed it

How to find numbers that appear only once in an integer array

You can use the hashMap method to achieve this. The steps are as follows:

(Video tutorial recommendation: java course)

1 , The key in the HashMap stores the number of the array array, and the value stores the number of values ​​​​in the array;

2. Traverse the HashMap, find the key whose Value value is equal to 1, and store it in the new array temp ;

3. Assign the values ​​in the array temp to num1, num2;

The code is as follows:

import java.util.Map;
import java.util.HashMap;
import java.util.Set;
public class Solution {
    public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
        Map<Integer,Integer> map=new HashMap();
        for(int i=0;i<array.length;i++){
            if(map.containsKey(array[i])){
                int len=map.get(array[i]);
                map.put(array[i],len+1);
            }else{
                map.put(array[i],1);
            }
        }
        int[] temp=new int[2];
        int index=0;
        Set<Map.Entry<Integer, Integer>> sm=map.entrySet();
        for (Map.Entry<Integer, Integer> entry : sm) {
            int t1=entry.getKey();
            int t2=entry.getValue();
            if(t2==1){
                temp[index++] = t1;
            }
        }
        num1[0]=temp[0];
        num2[0]=temp[1];
    }
}
Copy after login

For more tutorials, please visit java Getting Started Tutorial column.

The above is the detailed content of How to find numbers that appear only once in an integer array. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template