Leetcode: Find the traitor in the twins array!

这是一道来自leetcode的简单题目,第一次接触到了使用异或运算符进行解答。

topic

Given an array of non-empty integers, except for an element that appears only once, every other element appears twice. Find the element that appears only once.

Brute force traversal

var singleNumber = function(nums){
    
    
	let i = 0 ,j = 0 ;
	for(i=0;i<nums.length;i++){
    
    
		for(j=0;j<nums.length;j++){
    
    
			if(i != j && nums[i] == nums[j]){
    
    
				break;
			};
		};
		if(j == nums.length){
    
    
			return nums[i];
		};
	}
}

XOR operator to solve problems

/**
 * @param {number[]} nums
 * @return {number}
 */
var singleNumber = function(nums) {
    
    
    for(let i=1;i<nums.length;i++){
    
    
        nums[0] = nums[0] ^ nums[i];
    }
    return nums[0]
};

Guess you like

Origin blog.csdn.net/yivisir/article/details/108517635