[LeetCode] Single Number

題目

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

------------------------------------------------------------------------------------------------------------------------------------------------

我的思考是這樣,先排序然後兩個兩個一組尋找(因為題目是只有一個數出現一次,其它都出現兩次)

排序的部分是參考 QuickSort

 1 public class Solution {
 2     public int SingleNumber(int[] nums) {
 3         QuickSort(ref nums, 0, nums.Length -1);
 4         
 5         if (nums.Length == 1) return nums[0];
 6 
 7             for(int i = 0; (i + 2) < nums.Length; i += 2)
 8             {
 9                 if (nums[i] != nums[(i + 1)]) return nums[i];
10             }
11 
12             return nums[nums.Length - 1];
13     }
14     void Swap(ref int[] arr,int a, int b)
15         {
16             int temp = arr[a];
17             arr[a] = arr[b];
18             arr[b] = temp;
19         }
20 
21         int Partition(ref int[] arr,int front,int end)
22         {
23             int i = front - 1;
24             int j = front;
25             int pivot = arr[end];
26 
27             for(;j < end; j++)
28             {
29                 if(pivot> arr[j])
30                 {
31                     i++;
32                     Swap(ref arr,i,j);
33                 }
34             }
35             i++;
36             Swap(ref arr, i, end);
37             return i;
38 
39         }
40 
41         void QuickSort(ref int[] arr,int front,int end)
42         {
43             if(front < end)
44             {
45                 int middle = Partition(ref arr, front, end);
46                 QuickSort(ref arr, front, middle - 1);
47                 QuickSort(ref arr, middle + 1, end);
48             }
49             
50         }
51 }

 有過,不過這速度真慘

 改用MS內建的sort

public class Solution {
    public int SingleNumber(int[] nums) {
        //QuickSort(nums, 0, nums.Length -1);
        Array.Sort(nums);
        if (nums.Length == 1) return nums[0];

            for(int i = 0; (i + 2) < nums.Length; i += 2)
            {
                if (nums[i] != nums[(i + 1)]) return nums[i];
            }

            return nums[nums.Length - 1];
    }
}

 

有700ms的差距 QQ

猜你喜欢

转载自www.cnblogs.com/seako/p/10493605.html