//★题目:奇数下标都是奇数或者偶数下标都是偶数
//要求:给定一个长度不小于2的数组arr,实现一个函数调整arr
// 要么让所有的偶数下标都是偶数,要么让所有的奇数下标都是奇数
// 时间复杂度O(N),空间复杂度O(1)
#include <iostream>
#include <vector>
using namespace std;
void modify(vector<int> &matrix);
void swapVec1(vector<int> &matrix, int i, int j);
void printVector1(vector<int> matrix);
vector<int> generateDesignated1Vector(int *arr, int size);
int main()
{
int arrayMine[7] = { 1, 2, 3, 4, 5, 6, 7 };
int *arr = arrayMine;
vector<int> matrix = generateDesignated1Vector(arr, 7);
printVector1(matrix);
cout << endl;
modify(matrix);
printVector1(matrix);
cout << endl;
system("pause");
return 0;
}
void modify(vector<int> &matrix)
{
if (matrix.size()<2)
{
return;
}
int lastIndex = matrix.size() - 1;
int singleIndex = 1;
int doubleIndex = 0;
while ((singleIndex <= lastIndex) && (doubleIndex + 2 <= lastIndex))
{
if (matrix[lastIndex] % 2 == 0)
{
swapVec1(matrix, doubleIndex, lastIndex);
doubleIndex += 2;
}
else
{
swapVec1(matrix, singleIndex, lastIndex);
singleIndex += 2;
}
}
}
void swapVec1(vector<int> &matrix,int i ,int j)
{
int tmp = matrix[i];
matrix[i] = matrix[j];
matrix[j] = tmp;
}
//leftUnique
void printVector1(vector<int> matrix)
{
int size = matrix.size();
for (int i = 0; i < size; i++)
{
cout << matrix[i] << " ";
}
}
vector<int> generateDesignated1Vector(int *arr, int size)
{
int setNum = 0;
int arrIndex = 0;
vector<int> result;
if (size == 0)
{
return result;
}
static int vecIndex = 0;
while (vecIndex < size)
{
setNum = arr[arrIndex];
arrIndex++;
result.push_back(setNum);
vecIndex++;
}
return result;
}
数组与矩阵:奇数下标都是奇数或者偶数下标都是偶数
最新推荐文章于 2021-11-01 20:34:22 发布