程序员面试金典84题之每日7题 - 第十天

第一题:最小调整有序

题目:

有一个整数数组,请编写一个函数,找出索引m和n,只要将m和n之间的元素排好序,整个数组就是有序的。注意:n-m应该越小越好,也就是说,找出符合条件的最短序列。

给定一个int数组A和数组的大小n,请返回一个二元组,代表所求序列的起点和终点。(原序列位置从0开始标号,若原序列有序,返回[0,0])。保证A中元素均为正整数。

测试样例:

[1,4,6,5,9,10],6

返回:

[2,3]

解析:

用B复制A,对B进行排序,然后比较A和B的每一位,得出符合条件的最短序列

class Rearrange {
   
public:
	vector<int> findSegment(vector<int> A, int n) {
   
		// write code here
		vector<int> res(2, 0);
		vector<int> B = A;
		sort(B.begin(), B.end());
		int left = 0;
		int right = n - 1;
		while (left <= right) {
   
			if(B[left] == A[left]) ++left;
			if (B[right] == A[right]) --right;
			if (B[left] != A[left] && B[right] != A[right]) break;
		}
		if (left < right) {
   
			res[0] = left;
			res[1] = right;
		}
		return res;
	}
};

第二题:数字发音

题目:

有一个非负整数,请编写一个算法,打印该整数的英文描述。

给定一个int x,请返回一个string,为该整数的英文描述。

测试样例:

1234

返回:

“One Thousand,Two Hundred Thirty Four”

解析:

const vector<string> belowTen{
    "", "One", "Two", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine" };
const vector<string>  belowTwenty{
    "Ten", "Eleven", "Twelve", "Thirteen",
"Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
const vector<string>  belowHundred{
    "", "Ten", "Twenty", "Thirty", "Forty",
"Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };
class ToString {
   
public:
	string toString(int x) {
   
		// write code here
		if (x == 0) return "Zero";
		return transform(x);
	}
	string transform(int x){
   
		string re = "";
		if (0 == x)
			return re;
		if (x < 10)
			re = belowTen[x];
		
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值