目录
1.剑指Offer
面试题3:数组中重复的数字
题目描述:
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
代码:
class Solution {
public:
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
bool duplicate(int numbers[], int length, int* duplication) {
if(numbers==NULL||length<=0){
return false;
}
for(int i=0;i<length;i++){
if(numbers[i]<0||numbers[i]>length-1){
return false;
}
}
for(int i=0;i<length;i++){
while(numbers[i]!=i){
if(numbers[i]==numbers[numbers[i]]){
*duplication=numbers[i];
return true;
}
int temp=numbers[i];
numbers[i]=numbers[temp];
numbers[temp]=temp;
}
}
return false;
}
};
面试题4:二维数组中的查找
题目描述:在一个二维数组中(每个一维数组的长度相同),每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序。请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
代码:
class Solution {
public:
bool Find(int target, vector<vector<int> > array) {
int rows=array.size();
int cols=array[0].size();
if(array.empty()||rows<=0||cols<=0){
return false;
}
int row=0;
int col=cols-1;
while(row<rows&&col>=0){
if(array[row][col]==target){
return true;
}
else if(array[row][col]>target){
col--;
}
else{
row++;
}
}
return false;
}
};
2.Leetcode
例1:罗马数字转化为整数
题目描述:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
代码:
class Solution {
public:
int romanToInt(string s) {
int res=0;
int len=s.length();
if(len==0) return res;
for(int i=0;i<len;i++){
if(i>0&&(T(s[i])>T(s[i-1]))){
res+=(T(s[i])-2*T(s[i-1]));
}
else{
res+=T(s[i]);
}
}
return res;
}
int T(char c){
switch(c){
case 'I':return 1;
case 'V':return 5;
case 'X':return 10;
case 'L':return 50;
case 'C':return 100;
case 'D':return 500;
case 'M':return 1000;
default:return 0;
}
}
};
解析:
罗马数字记数方法
基本字符 | I | V | X | L | C | D | M |
---|---|---|---|---|---|---|---|
相应的阿拉伯数字表示为 | 1 | 5 | 10 | 50 | 100 | 500 | 1000 |
-
相同的数字连写、所表示的数等于这些数字相加得到的数、如:Ⅲ=3;
-
小的数字在大的数字的右边、所表示的数等于这些数字相加得到的数、 如:Ⅷ=8、Ⅻ=12;
-
小的数字(限于 I、X 和 C)在大的数字的左边、所表示的数等于大数减小数得到的数、如:Ⅳ=4、Ⅸ=9;
-
正常使用时、连写的数字重复不得超过三次;
-
在一个数的上面画一条横线、表示这个数扩大 1000 倍。
例2:整数转化为罗马数字
题目描述:
Given an integer, convert it to a roman numeral.
Input is guaranteed to be within the range from 1 to 3999.
代码:
class Solution {
public:
string intToRoman(int num) {
string one[]={"I","II","III","IV","V","VI","VII","VIII","IX"};
string ten[]={"X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
string hundred[]={"C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
string thoud[]={"M","MM","MMM"};
string roman="";
if(num>=1000){
roman+=thoud[num/1000-1];
num=num%1000;
}
if(num>=100){
roman+=hundred[num/100-1];
num=num%100;
}
if(num>=10){
roman+=ten[num/10-1];
num=num%10;
}
if(num>=1){
roman+=one[num%10-1];
}
return roman;
}
};