leetcode:136. Single Number

2018-08-18  本文已影响0人  唐僧取经

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
}
上一篇 下一篇

猜你喜欢

热点阅读