Java single number

来源:互联网 发布:微电影网络发行 编辑:程序博客网 时间:2024/06/08 10:51

需求:

给出2*n + 1 个的数字,除其中一个数字之外其他每个数字均出现两次,找到这个数字。

思路:

1、使用集合的方法

对于涉及到数组中重复元素的问题,可以考虑将数组中元素和角标存到HashMap中,然后遍历数组,看数组元素在Map集合中对应的值和该元素在数组中的角标是否相同,如果相同就直接返回该数,如果不同,就把Map集合中该元素对应的值变成该元素在数组中的角标。

2、使用指针

1)因为只有一个落单的数,其它都是成对存在,所以可以使用Arrays.sort(int[] arr)进行排序,这样重复的数字是相邻的。

2)遍历数组,比较该数与其右边的数,如果相同,就直接跳2个位置继续比较,如果不同,那就返回该值。

代码:

1、使用集合的方法

public class Solution {    /*     * @param A: An integer array     * @return: An integer     */    public int singleNumber(int[] A) {        // write your code here       HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>();       for(int  i = 0; i < A.length; i++)       {           hm.put(A[i], i);       }       for(int i = 0; i < A.length; i++)       {           if(i == hm.get(A[i]))           {               return A[i];           }           else           {               hm.put(A[i], i);           }       }       return 0;    }}
2、使用指针

public class Solution {    /*     * @param A: An integer array     * @return: An integer     */    public int singleNumber(int[] A) {        // write your code here        Arrays.sort(A);        for(int i = 0; i < A.length; )        {            if(i == A.length - 1)            {                return A[i];            }            j = i+1;            if(A[i] != A[j])            {                return A[i];            }            else            {                i = j+1;            }        }                return 0;    }}


原创粉丝点击