在 Array 中查找其位置形成算术级数的元素
给定一个包含N个整数的数组A[] 。考虑一个整数num 这样num 出现在数组A[]中,并且num的所有位置按升序排序形成算术级数。任务是打印所有这样的num对 以及它们形成的算术级数的共同差异。
例子 :
Input: N = 8, A = {1, 2, 1, 3, 1, 2, 1, 5}
Output: {1, 2}, {2, 4}, {3, 0}, {5, 0}
Explanation: Positions at which 1 occurs are: 0, 2, 4, 6
It can be easily seen all the positions have same difference between consecutive elements (i.e. 2).
Hence, positions of 1 forms arithmetic progression with common difference 2.
Similarly, all positions of 2 forms arithmetic progression with common difference 4.
And, 3 and 5 are present once only.
According to the definition of arithmetic progression (or A.P.), single element sequences are also A.P. with common difference 0.
Input: N = 1, A = {1}
Output: {1, 0}
方法:解决问题的想法是使用散列。
请按照以下步骤解决问题:
- 创建一个以整数作为键,整数向量作为键值的映射。
- 遍历数组并将数组中存在的每个元素的所有位置存储到map中。
- 遍历map,检查map中当前元素的所有位置是否形成AP
- 如果是这样,请将该元素与共同差异一起插入答案中。
- 否则,继续遍历地图
以下是上述方法的实现:
C++
// C++ code for above approach
#include
using namespace std;
// Function to print all elements
// in given array whose positions forms
// arithmetic progression
void printAP(int N, int A[])
{
// Declaring a hash table(or map)
// to store positions of all elements
unordered_map > pos;
// Storing positions of
// array elements in map
for (int i = 0; i < N; i++) {
pos[A[i]].push_back(i);
}
// Declaring a map to store answer
// i.e. key - value pair of element
// with their positions forming A.P.
// and their common difference
map ans;
// Iterating through the map "pos"
for (auto x : pos) {
// If current element is present
// only at 1 position, then simply
// insert the element in answer
// with common difference = 0
if (x.second.size() == 1) {
ans[x.first] = 0;
}
// If current element is present
// at more than one positions,
// then check if all the
// positions are at same difference
else {
bool flag = 1;
// Storing the difference of
// first two positions in
// variable "diff"
int diff = x.second[1] - x.second[0];
// Declaring "prev" to store
// previous position of
// current element
int prev = x.second[1];
//"curr" stores the
// Current position of the element
int curr;
// Iterating through all the
// positions of the current element
// and checking id they are in A.P.
for (auto it = 2;
it < x.second.size(); it++) {
curr = x.second[it];
if (curr - prev != diff) {
flag = 0;
break;
}
prev = x.second[it];
}
// If all positions of current
// element are in A.P.
// Insert it into answer with
// common difference as "diff"
if (flag == 1) {
ans[x.first] = diff;
}
}
}
// Printing the answer
for (auto it : ans) {
cout << it.first << " "
<< it.second << endl;
}
}
// Driver Code
int main()
{
int N = 8;
int A[] = { 1, 2, 1, 3, 1, 2, 1, 5 };
printAP(N, A);
}
Javascript
1 2
2 4
3 0
5 0
时间复杂度: O(N*log(N))
辅助空间: O(N)