美文网首页
56.数组中数字出现的次数(中等)

56.数组中数字出现的次数(中等)

作者: 今天柚稚了么 | 来源:发表于2020-02-22 14:49 被阅读0次

题目一描述:

数组中只出现一次的两个数字。一个整型数组 nums 里除两个数字之外,其他数字都出现了两次。请写程序找出这两个只出现一次的数字。

思路一:使用哈希表记录数字出现的次数

建立一个哈希表,键值Key是数字,值Value是数字出现的次数。从头开始扫描数组两次,第一次扫描,统计每个数字的出现次数;第二次扫描,从哈希表中得到该数字,如果该数字出现的次数为1,则返回这两个数字。

import java.util.HashMap;
//num1,num2分别为长度为1的数组。传出参数
//将num1[0],num2[0]设置为返回结果
public class Solution {
    public void FindNumsAppearOnce(int [] array,int num1[] , int num2[]) {
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i=0;i<array.length;i++){
            if(map.containsKey(array[i])){
                map.put(array[i],2);
            }else{
                map.put(array[i],1);
            }
            
        }
        int count = 0;
        for(int i=0;i<array.length;i++){
            if(map.get(array[i])==1){
                if(count==0){
                    num1[0]=array[i];
                    count++;
                }else{
                    num2[0]=array[i];
                }
            }
        }
    }

思路二:异或(没看太懂)

题目二描述:

在一个数组 nums 中除一个数字只出现一次之外,其他数字都出现了三次。请找出那个只出现一次的数字。
输入:nums = [9,1,7,9,7,9,7]
输出:1

思路一:使用哈希表

import java.util.HashMap;
class Solution {
    public int singleNumber(int[] nums) {
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        for(int i=0;i<nums.length;i++){
            if(map.containsKey(nums[i])){
                int value = map.get(nums[i]);
                map.put(nums[i],value+1);
            }else{
                map.put(nums[i],1);
            }
        }
        for(int i=0;i<nums.length;i++){
            if(map.get(nums[i])==1)
                return nums[i];
        }
        return 0;
    }
}

思路二:异或(没看太懂)

相关文章

网友评论

      本文标题:56.数组中数字出现的次数(中等)

      本文链接:https://www.haomeiwen.com/subject/kqrgfhtx.html