题目:
Given an integer array arr
。count element x
such that x+1
is also in arr
.
if there’re duplicates in arr
,count them seperately
给定一个整数的阵列,有多少个数字元素x
当其x+1
之后依然存在于arr
数组内。
Constraints:
· 1 <= arr.length <= 1000
· 0 <= arr[i] <= 1000
int countElements(int* arr, int arrSize){
//input:
//arr: [1,3,2,3,5,0], arrSize:6
//plus 1,4,3,4,6,1
//found 1,0,1,0,0,1
//相加 1+0+1+0+0+1=3
int arrPlus1[arrSize];
for (int i = 0; i < arrSize; i++){
plus1[i] = arr[i] + 1;
}
int found[arrSize]:
for(int i = 0; i < arrSize; i++){
//检查plus1[i]有没有在arr里出现
int count = 0;
for (int j = 0; j < arrSize; j++){
if(arr[j] == plus1[i]){
count++;
}
}
if(count >= 1){
found[i] = 1;
else
found[i] = 0;
}
}
int count = 0;
for(int i = 0; i <= arrSize; I++){
count+ =found[i];
}
return count;
}
上述方法产生了额外的阵列来储存plus1和found,简化后有以下形式:
int coountElement(int* arr, int arrSize){
int count = 0;
for (int i = 0; i < arrSize; i++){
int x = arr[i];
int xPlus1 = x + 1;
bool isFound = false;
for (in j = 0; j < arrSize; j++){
if (arr[j] == xPlus[i]){
isFound = true;
}
if (isFound){
count ++;
}
}
return count;
}
}
int coountElement(int* arr, int arrSize){
//因为数字是0~1000之间,所以会加到1001
//一开始全部都当作没找到
bool isFound[1002] = {false};//isFound[0]~isFound[1001]
for (i = 0; i < arrSize; i++){
isFound[arr[i]] = true;
}
int count = 0;
for (int i = 0; i < arrSize; i++){
int x = arr[i];
int xPlus1 = x + 1;
if (isFound[xPlus1]){
count++;
}
}
}