leetcode 260. Single Number III --> 用hashmap计算出现的次数,注意containsKey获取key,用 get 方法获取值

45 篇文章 1 订阅
28 篇文章 0 订阅

260. Single Number III

 
  My Submissions
  • Total Accepted: 42681
  • Total Submissions: 92409
  • Difficulty: Medium

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].

Note:

  1. The order of the result is not important. So in the above example, [5, 3] is also correct.
  2. Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

public class Solution {    //改完下面的语法错误,一次通过。。哎,语法错误。。。
    public int[] singleNumber(int[] nums) {
        HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
        int length = nums.length;//注意获得数组的长度,不是length(),而是直接 .length
        if(length<=1)return nums;
        for(int i=0;i<length;i++){
            if(hm.containsKey(nums[i])==false) //注意没有getKey方法,只有containsKey方法,返回值为Boolean型
                hm.put(nums[i],1);
            else{
                int temp = hm.get(nums[i])+1;//注意用get方法获取值
                hm.put(nums[i],temp);
            }
        }
        LinkedList<Integer> list = new LinkedList<Integer>();
        for(int i:hm.keySet()){
            if(hm.get(i)==1)//注意没有getValue方法,只有get方法获取值
            list.add(i);
        }
        int[] ret= new int[list.size()];//注意数组的初始化
        //Collections.addAll(ret,list);//类型不对应
        //return list.toIntegerArray();//注意没toIntegerArray()方法
        for(int i=0;i<list.size();i++){ //注意list长度是.size()方法
            ret[i]=list.get(i);
        }
        return ret;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值