flowingfog

偶尔刷题

  博客园  :: 首页  :: 新随笔  :: 联系 ::  :: 管理

分析

难度 易

来源

https://leetcode.com/problems/single-number

题目

Given a non-empty 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?

Example 1:

Input: [2,2,1]
Output: 1

Example 2:

Input: [4,1,2,1,2]
Output: 4

解答

 1 package LeetCode;
 2 
 3 public class L136_SingleNumber {
 4     public int singleNumber(int[] nums) {
 5         int result=0;
 6         for(int i=0;i<nums.length;i++){
 7             result^=nums[i];
 8         }
 9         return result;
10     }
11     public static void main(String[] args){
12         L136_SingleNumber l136=new L136_SingleNumber();
13         //int[] nums={2,2,1};
14         int[] nums={4,1,2,1,2};
15         System.out.println(l136.singleNumber(nums));
16     }
17 }

 

posted on 2018-11-06 20:53  flowingfog  阅读(41)  评论(0编辑  收藏