[Leetcode]-Reverse Integer
Question: Given an array of size n, find the majority element. The majority element is the element that appears more? N/2? Times.
Find out if the value in the array exceeds? N/2? Secondary data
Three solutions:
1. A clever solution based on others'
2. Insert sorting. After sorting, nums? N/2? Must it exceed? N/2? And when the inserted data is close to the sorted order, the time complexity is O (n)
3. Fast sorting, the same as 2, but the speed is slightly faster than 12 ms
You may assume that the array is non-empty and the majority element always exist in the array.
typedef int elementtype;//infact CUT = 10 is the best solution#define CUT 10 void swap(int *a,int *b) { int tem = *a; *a = *b; *b = tem; } void insertion(elementtype A[],int n) { int p = 0 ; int j = 0 ; for(p=1;p
0&&A[j-1]>tem;j--) { A[j] = A[j-1]; } A[j] = tem; } } elementtype median3(elementtype A[],int left ,int right) { int center = (left +right) / 2; if(A[left]>A[center]) swap(&A[left],&A[center]); if(A[left]>A[right]) swap(&A[left],&A[right]); if(A[center]>A[right]) swap(&A[center],&A[right]); swap(&A[center],&A[right-1]); return A[right-1]; } void Qsort(elementtype A[],int left, int right) { int i,j; elementtype pivot; if(left + CUT<= right) { pivot = median3(A,left,right); //select middle element as pivot i = left;j = right-1; for(;;) { while(A[++i]
pivot){} if(i
0&&nums[j-1]>tem;j--) { nums[j] = nums[j-1]; } nums[j] = tem; } return nums[numsSize/2]; */ //solution 3 qiuk sort :12ms Qsort(nums,0,numsSize-1); return nums[numsSize/2];}