leetcode--singnal num

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

Note:

our algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

解题思路:使用异或操作,这样就可以知道到底是哪一个是单独的。

java版本:

package leedcode;

public class test {

    private static int singnalnum(int[] nums) {
        int res = 0;
        for (int i = 0; i < nums.length; i++)
            res ^= nums[i];//异或操作
        return res;
    }

    // 主方法
    public static void main(String[] args) {
        int[] s = { 1, 2, 3, 1, 2 };
        int a = singnalnum(s);
        System.out.println("the singlnal num is:" + a);
    }
}

c版本:

int singleNumber(int* nums, int numsSize) {
    int i;
    int ans=0;
       for (i=0;i<numsSize;i++)
       {
           ans=ans^nums[i];
       }
       return ans;
}

你可能感兴趣的:(LeetCode,singnalnum)