当前位置: 首页 > 工具软件 > Magic > 使用案例 >

Magic index

乐刚毅
2023-12-01
find the index with value equal to index. Time Complexity: O(logn), Space Complexity: O(1).
	//numbers are distinct
	public int getMagic(int[] a, int start, int end) {
		if(start > end) return -1;
		int middle = start + (end - start) / 2;
		if(a[middle] == middle) return middle;
		else if(a[middle] > middle) return getMagic(a, start, middle - 1);
		else return getMagic(a, middle + 1, end);
	}
	
	//if numbers are not distinct, means have repeated numbers
	public int getMagic2(int[] a, int start, int end) {
		if(start > end) return -1;
		int middle = start + (end - start) / 2;
		if(a[middle] == middle) return middle;
		
		//search left
		//the min leftIndex should be compare with the value 
		int leftIndex = Math.min(middle - 1, a[middle]);
		int left = getMagic2(a, start, leftIndex);
		if(left >= 0) return left;
		
		//search right 
		int rightIndex = Math.max(middle + 1, a[middle]);
		int right = getMagic2(a, rightIndex, end);
		return right;
	}

 类似资料:

相关阅读

相关文章

相关问答