LeetCode:Single Number

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. 

给出一个整型数组,其中除了一个元素之外,其他元素均出现两次,要求找出这个只出现一次的元素。

题目要求使用线性的时间复杂度。


解题思路:

若使用暴力解决的方法,使用两个循环,针对每个元素遍历整个数组的其他元素,判断是否有相同的元素,若没有相同的元素,则返回当前元素。这种方法的时间复杂度为O(N^2),显然不符合要求。

第二种方法,使用空间换时间的思想,使用一个哈希表遍历一次整个数组来存储数组各个元素出现的个数,随后再遍历一次,若当前元素在哈希表中的Value值为1,则返回当前元素。这种方法的时间复杂度为O(n),符合要求。


代码如下:

public class Solution {
    public int singleNumber(int[] nums) {
        Map<String, Integer> map = new HashMap<String, Integer>();
        int length = nums.length;
        for(int i=0; i<length; i++){
            String numstr = nums[i] + "";
            if(map.get(numstr) !=null && map.get(numstr) == 1){
                map.put(numstr, 2);
            }else{
                map.put(numstr, 1);
            }
        }
        for(int i=0; i<length; i++){
            String numstr = nums[i] + "";
            if(map.get(numstr) == 1){
                return nums[i];
            }
        }
        
        return -1;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章