【LeetCode-面試演算法經典-Java實現】【136-Single Number(只出現一次的數字)】
阿新 • • 發佈:2018-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?
題目大意
給定一個數組,每個元素都出現2次除了其中的一個,找出只出現一次的數字注意:演算法必須是線性時間複雜度,可以不使用額外空間實現嗎?
解題思路
使用異或運算。
程式碼實現
演算法實現類
public class Solution {
public int singleNumber(int[] nums) {
if (nums == null || nums.length < 1) {
throw new IllegalArgumentException("nums");
}
for (int i = 1; i< nums.length; i++) {
nums[0] ^= nums[i];
}
return nums[0];
}
}
評測結果
點選圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中檢視完整圖片。