[LeetCode] Single Number

本文探讨了一种在整数数组中找出唯一出现一次元素的算法,该算法具备线性运行时间复杂度且尽量避免额外内存使用。通过对比自定义快速排序与.NET内置排序方法,展现了不同实现方式的性能差异。

題目

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

 

转载于:https://www.cnblogs.com/seako/p/10493605.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值