Cholerae Hu,
The assignment proceeds in two phases. First, the operands of index
expressions <https://golang.org/ref/spec#Index_expressions> and pointer
indirections <https://golang.org/ref/spec#Address_operators> (including
implicit pointer indirections in selectors
<https://golang.org/ref/spec#Selectors>) on the left and the expressions on
the right are all evaluated in the usual order
<https://golang.org/ref/spec#Order_of_evaluation>. Second, the assignments
are carried out in left-to-right order.
https://golang.org/ref/spec#Assignments
package main
import (
"fmt"
)
func main() {
test := []int{2, 1, 1}
fmt.Println(findDuplicate(test))
}
func findDuplicate(nums []int) int {
for i := 0; i < len(nums); i++ {
if nums[i] != i+1 {
if nums[i] == nums[nums[i]-1] {
return nums[i]
}
// nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]
t1, t2 := nums[nums[i]-1], nums[i]
nums[i], nums[nums[i]-1] = t1, t2
}
}
return 0
}
Output:
1
Peter
On Thursday, March 23, 2017 at 1:04:00 AM UTC-4, Cholerae Hu wrote:
>
> First code:
> package main
> import (
> "fmt"
> )
>
>
> func main() {
> test := []int{2, 1, 1}
> fmt.Println(findDuplicate(test))
> }
> func findDuplicate(nums []int) int {
> for i := 0; i < len(nums); i++ {
> if nums[i] != i+1 {
> if nums[i] == nums[nums[i]-1] {
> return nums[i]
> }
>
> //tmp := nums[i]
> //nums[i] = nums[nums[i]-1]
> //nums[nums[i]-1] = tmp
>
> nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]
> }
> }
> return 0
> }
> These code will print 1.
>
> Second code:
> package main
> import (
> "fmt"
> )
>
>
> func main() {
> test := []int{2, 1, 1}
> fmt.Println(findDuplicate(test))
> }
> func findDuplicate(nums []int) int {
> for i := 0; i < len(nums); i++ {
> if nums[i] != i+1 {
> if nums[i] == nums[nums[i]-1] {
> return nums[i]
> }
>
> tmp := nums[i]
> nums[i] = nums[nums[i]-1]
> nums[nums[i]-1] = tmp
>
> //nums[i], nums[nums[i]-1] = nums[nums[i]-1], nums[i]
> }
> }
> return 0
> }
> These code will print 0.
>
> Is it a bug or something? I'm quite confused. Thanks!
>
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.