lintcodeleetcode由易至难第14题:Single Number

xiaoxiao2021-02-28  88

Problem:

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?

Code:

public class Solution { public int singleNumber(int[] nums) { Arrays.sort(nums); if (nums.length == 1 || nums[0] != nums[1]){ //数组可能只有一个元素 return nums[0]; } for(int i = 1; i < nums.length-1; i++){ if((nums[i] != nums[i-1]) && (nums[i] != nums[i+1])){ return nums[i]; } } return nums[nums.length - 1]; //我的方法好像比较笨 } }

Code2:

public class Solution { public int singleNumber(int[] nums) { int n = 0; for(int i = 0; i < nums.length; i++){ n = n ^ nums[i]; //这类题有个大杀器叫异或!!! } return n; } }

转载请注明原文地址: https://www.6miu.com/read-81628.html

最新回复(0)