代码改变世界

判断数组中是否有相同的数

2009-09-13 18:10  Kevin Pan  阅读(1025)  评论(0编辑  收藏  举报

Given an array of size N in which every number is between 1 and N, determine if there are any duplicates in it. You are allowed to destroy the array if you like. [ I ended up giving about 4 or 5 different solutions for this, each supposedly better than the others ].

给定一个大小为N的数组,每一个数都是在1N之间,判断里面是不是有重复的数。可以将破坏原数组。
            int[] arr = new int[] { 5, 2, 4, 7, 4, 6, 1 };
            bool result = true;
            for (int i = 0; i < arr.Length - 1; i++)
            {
                for (int j = i+1; j < arr.Length - 1; j++)
                {
                    if (arr[i] == arr[j])
                    {
                        result = false;
                        break;
                    }
                }
                if (result == false)
                {
                    break;
                }
            }
希望高手们更给出更优秀的算法