数组旋转

/*
问题描述:给定一个2维数组,将数组中的元素旋转90度,空间复杂度为O(1)
来源:网易算法课
日期:2017-10-23
*/
#include <iostream>
using namespace std;

class ArrayRotation{
public:
	ArrayRotation(int n)
	{
		size = n;

		arr = new int *[n];
		for (int i = 0; i < n; i++)
			arr[i] = new int[n];

		for (int i = 0; i < n; i++)
		{
			for (int j = 0; j < n; j++)
				arr[i][j] = i*n + j + 1;
		}

		top = 0;
		right = n - 1;
		bottom = n - 1;
		left = 0;

		top_mov = left;
		right_mov = top;
		bottom_mov = right;
		left_mov = bottom;
		
	}
	void printArray()
	{
		while (top < bottom && left < right)
		{
			top_val = arr[top][top_mov];
			right_val = arr[right_mov][right];
			bottom_val = arr[bottom][bottom_mov];
			left_val = arr[left_mov][left];

			arr[top][top_mov] = left_val;
			arr[right_mov][right] = top_val;
			arr[bottom][bottom_mov] = right_val;
			arr[left_mov][left] = bottom_val;

			top_mov++;
			right_mov++;
			bottom_mov--;
			left_mov--;

			if (top_mov >= right)
			{
				top++;
				right--;
				bottom--;
				left++;

				top_mov = left;
				right_mov = top;
				bottom_mov = right;
				left_mov = bottom;
			}

		}

		for (int i = 0; i < size; i++)
		{
			for (int j = 0; j < size; j++)
				cout << arr[i][j] << " ";
			cout << endl;

		}
	}

	
private:
	int **arr;
	int top, left, right, bottom;
	int top_mov, left_mov, right_mov, bottom_mov;
	int top_val, left_val, right_val, bottom_val;
	int size;
};
int main()
{
	ArrayRotation ar(4);
	ar.printArray();

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值