《leetcode》single-number

来源:互联网 发布:centos ftp 根目录 编辑:程序博客网 时间:2024/06/18 12:26

题目描述

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. Could you implement it without using extra memory?

解析:该题目暴力求解当然是可以通过的,但是不满足题目的要求,题目要求时间复杂度为O(n)。

代码一:暴力求解,不建议

import java.util.*;public class Solution {    public int singleNumber(int[] A) {        List<Integer> list = new ArrayList<>();        for(int i:A){            list.add(i);        }        Set<Integer> set = new HashSet<>(list);        for(int i:set){            int temp =i;            int count=0;            for(int j:A){                if(j==i){                    count++;                }            }            if(count==1){                return temp;            }        }        return -1;    }}

代码二:利用异或的计算特点。
1)相同的数异或为0,例如 6^6=0;
2)0异或不为0的数为不为0的数,例如:0^5=5

public static int singleNumber(int[] A) {    int num = 0;    for(int i=0;i<A.length;i++){        num^=A[i];    }    return num;}
原创粉丝点击