136. Single Number
Description
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
Answer
package main
import "fmt"
func singleNumber(nums []int) int {
var result int = -1
var flag bool = false
for i := 0; i < len(nums); i++ {
flag = false
for j := 0; j < len(nums); j++ {
if nums[i] == nums[j] && i != j {
result = nums[i]
flag = true
break
}
}
if flag == false {
result = nums[i]
break
}
}
return result
}
func main() {
a := []int{4, 1, 2, 1, 2}
fmt.Println(singleNumber(a))
}
Answer
func singleNumber(nums []int) int {
var result int
for i:=0;i<len(nums) ;i++ {
result^=nums[i]
}
return result
}
网友评论