前面做了下线性表有关的操作,主要是去除线性表中的重复值,(数组和链表),这一篇做两道在线性表中查找的题目。
LeetCode线性表的操作(Remove Duplicates)
int findSpecialPosition( int a[ ], int n ) { int begin = 0; int end = n - 1; int half = ( begin + end ) >> 1; //get the pivot if( a[ begin ] < a[ end ] )//sorted return end; while( half + 1 <= end && a[ half ] < a[ half + 1] && begin <= end ) { if( a[ half ] >= a[ begin ] ) { begin = half + 1; } else end = half - 1; half = ( begin + end ) >> 1; } return half; }把4种特殊的情况都测试一遍就可以通过了,下面根据half 返回的值,可以把原数组分为2个排序好的数组,在排序好的数组中进行二分查找法。
int SearchBinary( int A[], int begin, int end, int target ) { if( begin <= end ) { int half = ( begin + end ) >> 1; while( A[ half ] != target && begin <= end ) { if( A[ half ] > target ) end = half - 1; else begin = half + 1; half = ( begin + end ) >> 1; } if( A[ half ] == target ) return half; else return -1; } else return -1; } int search(int A[], int n, int target) { int begin = 0; int end = n - 1; int half = ( begin + end ) >> 1; if( A[ begin ] < A[ end ] )//sorted SearchBinary( A,0 ,n - 1, target ); while( half + 1 <= end && A[ half ] < A[ half + 1] && begin <= end ) { if( A[ half ] >= A[ begin ] ) { begin = half + 1; } else end = half - 1; half = ( begin + end ) >> 1; } begin = 0; end = n - 1; if( half + 1 <= end &&A[ half + 1 ] <= target && target <= A[ end ] ) return SearchBinary( A, half + 1, end, target ); else return SearchBinary( A, begin, half , target ); }//时间复杂度为o(n),空间复杂度o(1)
int search(int A[], int n, int target) { int first = 0; int end = n - 1; int half = ( first + end ) >> 1; while( first <= end ) { if( target == A[ half ]) return half; if( A[ half ] >= A[ first ] )//在数组前面部分, { if( A[ half ] >= target && A[ first ] <= target ) end = half; else first = half + 1; } else { if( A[ half ] <= target && target <= A[ end ] ) first = half; else end = half - 1; } half = ( first + end ) >> 1; } return -1; }
bool search(int A[], int n, int target) { int first = 0; int end = n - 1; int half = ( first + end ) >> 1; while( first <= end ) { if( target == A[ half ]) return true; if( A[ half ] > A[ first ] )//在数组前面部分,这个部分是不变的 { if( A[ half ] >= target && A[ first ] <= target ) end = half; else first = half + 1; } else if( A[ half ] < A[ first ]) { if( A[ half ] <= target && target <= A[ end ] ) first = half; else end = half - 1; } else first++; half = ( first + end ) >> 1; } return false; }