剑指offer--字符串的排列、数组中出现次数超过一半的数字

开宗明义:本系列基于牛客网剑指offer,刷题小白,一天两道我快乐!旨在理解和交流,重在记录,望各位大牛指点!


牛客网-剑指offer



1、字符串的排列

描述输入一个字符串,按字典序打印出字符串中字符的所有排列。例如输入字符为 a b c abc abc ,则打印出由字符 a , b , c a,b,c a,b,c 所能排列出来的所有字符串 a b c , a c b , b a c , b c a , c a b , c b a abc,acb,bac,bca,cab,cba abc,acb,bac,bca,cab,cba,输入要求:输入的字符串,长度不超过9,可能有重复字符,字符只包括大小写字母

思路: 递归法:先固定第一个字符,求剩余字符的排列;这跟求原字符排列一样的问题。

  1. 遍历出所有可能出现的第一个位置的字符(依次将第一个字符同后面所有字符交换);
  2. 固定第一个字符,求后面字符的排列(插入递归进行实现);

测试代码:

#include <vector>
#include <stdio.h>
#include <algorithm>
using namespace std;
//
class Solution {
public:
	vector<string>	Permutation(string str) {
		vector<string>	result;
		//
		if (str.empty())
			return result;
		//
		Permutation(str, result, 0);
		//此时得到的result中排列并不是字典顺序,可以单独再排下序
		sort(result.begin(), result.end());

		return result;
	}
	//
	void Permutation(string str, vector<string> &result, int begin) {
		if (begin == str.size() - 1) {	//递归结束条件:索引已经指向str最后一个元素时
			if (find(result.begin(), result.end(), str) == result.end()) {
				//如果result中不存在str,才添加;避免重复添加的情况
				result.push_back(str);
			}
		}
		else {
			//第一次循环 i 与 begin 相等,相当于第一个位置自身交换,关键在于之后的循环
			//之后 i!= begin,则会交换两个不同位置上的字符,直到 begin == str.size()-1,进行输出
			for (int i = begin; i < str.size(); ++i) {
				swap(str[i], str[begin]);
				Permutation(str, result, begin + 1);
				swap(str[i], str[begin]);	//复位,用以恢复之前字符串的顺序,达到第一位依次跟其他位交换的目的
			}
		}
	}
};


2、数组中出现次数超过一半的数字

描述:数组中有一个数字出现次数超过数组长度的一半,请找出这个数字。例如输入一个长度为9的数组{1,2,3,2,2,2,5,4,2}。输出2,不存在则输出0。

思路1:数组排序后,如果符合条件的数存在,则一定是数组中间的那个数 ,涉及快速排序。

测试代码:

#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
	int MoreThanHalfNum_Solution(vector<int> numbers) {
		//用到了sort,时间复杂度为O(N*logN),并非最优
		if (numbers.empty())
			return 0;
		//
		sort(numbers.begin(), numbers.end());	//排序,取数组中间的那个数
		int middle = numbers[numbers.size() / 2];

		int count = 0;	//出现次数
		for (int i = 0; i < numbers.size(); ++i) {
			if (numbers[i] == middle) {
				++count;
			}
		}
		return (count > numbers.size() / 2) ? middle : 0;
	}
};


思路2: 遍历数组时,保存两个值,一个是数字,一个是该数字出现的次数,这边巧妙地运用到一个 trick,题目要求这个属于大于一半,那么它出现的次数比其他所有数字出现的次数和还要多。

测试代码:

#include <vector>
#include <algorithm>
using namespace std;

class Solution {
public:
	int MoreThanHalfNum_Solution(vector<int> numbers) {
		if (numbers.empty())
			return 0;
		//
		int result = numbers[0];
		int times = 1;	//次数
		//
		for (int i = 1; i < numbers.size(); ++i) {
			//
			if (times == 0) {
				result = numbers[i];
				times = 1;
			}
			else {
				if (numbers[i] == result)
					++times;
				else
					--times;
			}
		}
		//上面是求的result
		int times1 = 0;
		for (int i = 0; i < numbers.size(); ++i) {
			if (numbers[i] == result)
				++times1;
		}
		
		return (times1 > numbers.size() / 2) ? result : 0;
	}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值