Rotated array related program. 和旋转数组相关的几个程序

问题一:将一个具有n个元素的数组向右旋转i个位置。

EXAMPLE:

Input: 将(1, 2, 3, 4, 5, 6, 7, 8, 9)旋转3个位置

Output: (7, 8, 9, 1, 2, 3, 4, 5, 6)


问题二:(Cracking the coding interview 9.3)Given a sorted array of n integers that has been rotated an unknown number of times, give an O(log n) algorithm that finds an element in the array. You may assume that the array was originally sorted in increasing order.

EXAMPLE:

Input: find 5 in array (15 16 19 20 25 1 3 4 5 7 10 14)

Output: 8 (the index of 5 in the array)

思路:仍然采用二分法进行搜索,搜索的时候多加一些判断。

int FindRotatedSortedArray(const int nVal, const int *pArr, const int nlength)
{
	int idxL = 0;;
	int idxR = nlength - 1;
	int idxM = (idxL + idxR) / 2;
	while (idxR >= idxL)
		{
		idxM = (idxL + idxR) / 2;
		if (nVal == pArr[idxM])
			return idxM;

		if (pArr[idxL] < pArr[idxR])// arr not rotated.  10 ,,,, 15 ,,,, 20
			{
			if (pArr[idxM] > nVal)	//search left
				idxR = idxM - 1;
			else					//search right
				idxL = idxM + 1;
			}
		else
			{
			if (pArr[idxM] < pArr[idxL] && pArr[idxM] < pArr[idxR]) // 20 ,,,, 5 ,,,, 10
				{
				if (nVal < pArr[idxM] || nVal >= pArr[idxL])	// 20 ,(25 ,, 4), 5 ,,,, 10
					idxR = idxM - 1; //search left
				else						// 20 ,,,, 5 ,,(6),, 10
					idxL = idxM + 1; // search right
				}
			else if (pArr[idxM] >= pArr[idxL] && pArr[idxM] > pArr[idxR])// 20 ,,,, 25 ,,,, 10
				{
				if (nVal > pArr[idxM] || nVal <= pArr[idxR])			// 20 ,,,, 25 ,(30 ,, 5), 10
					{
					idxL = idxM + 1; //search right
					}
				else // 20 ,,(23),, 25 ,,,, 10
					{
					idxR = idxM - 1; //search left
					}
				}
			}
		}
	return -1;
}

问题三:Given a sorted array of n integers that has been rotated an unknown number of times, give an O(log n) algorithm that finds the index of the minimum element.

EXAMPLE:

Input: find 5 in array (15 16 19 20 25 1 3 4 5 7 10 14)

Output: 5 (the index of 1 in the array)

int FindMinimun(const int *pArr, const int nLength)
{
	if (NULL == pArr)
		return -1;
	
	int idxL = 0;
	int idxR = nLength - 1;
	int idxM;
	while (idxL <= idxR)
		{
		if (pArr[idxL] <= pArr[idxR])					// ,,, 5, ,,, 10, ,,,
			return idxL;
		
		if (idxL + 1 == idxR && pArr[idxL] > pArr[idxR])// ,,, 10, 1, ,,,
			return idxR;
		
		idxM = (idxL + idxR)/2;
		if (pArr[idxM] >= pArr[idxL])		// ,,, 10, ,,, 20, ,,, 1, ,,,
			idxL = idxM + 1;
		else if (pArr[idxM] <= pArr[idxR])  // ,,, 10, ,,, 5, ,,, 9, ,,,
			idxR = idxM;
		else
			return -1;
		}
	return -1;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值