您的位置:首页 > 其它

lintcode 主元素

2015-12-05 16:44 337 查看
给定一个整型数组,找出主元素,它在数组中的出现次数严格大于数组元素个数的二分之一。

样例

给出数组[1,1,1,1,2,2,2],返回 1

挑战

要求时间复杂度为O(n),空间复杂度为O(1)
题解1 时间复杂度O(nlogn),题解2 时间复杂度 O(n), 题解3O(n)但比2较好。

题解1

class Solution {

public:

/**

* @param nums: A list of integers

* @return: The majority number

*/

void swap(vector<int>&nums,int i, int j) {

int temp = nums[i];

nums[i] = nums[j];

nums[j] = temp;

}

void sort(vector<int>&nums,int left,int right) {

if (left >= right) return;

int i = left,j = right,temp = nums[left];

while(i < j) {

while(nums[j] >= temp && i < j) --j;

while (nums[i] <= temp && i< j) ++i;

if (i < j) {

swap (nums,i,j);

}

}

nums[left] = nums[i];

nums[i] = temp;

sort(nums,left,i - 1);

sort(nums,i + 1,right);

}

int majorityNumber(vector<int> nums) {

// write your code here

int lenth = nums.size() - 1;

sort(nums,0,lenth);

return nums[lenth / 2];

}

};

题解 2 利用求第k大数 求得 中间的那个数就是主元素

题解 3

class Solution {

public:

/**

* @param nums: A list of integers

* @return: The majority number

*/

int majorityNumber(vector<int> nums) {

// write your code here

int i,majorityNum,repeatTimes = 0,lenth = nums.size();

for(i = 0;i<lenth;i++){

if(repeatTimes == 0){

majorityNum = nums[i];

repeatTimes = 1;

} else {

if(majorityNum == nums[i])

++repeatTimes;

else

--repeatTimes;

}

}

return majorityNum;

}

};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: