leetcode1:线性表
//定义二维数组
int **array = new int*[row_num]; for(int i=0;i<row_num;i++) { array[i] = new int[col_num]; }
vector<vector<int>> v2(row_num,vector<int>(col_num,0));
//删除排好序数组中重复的数据,返回剩余数组的长度
//int A[]: input array
//len: the array length
//dup: the times that duplicates can be allowed
//return the length of the result array
int removeDuplicate(int A[],int len,int dup) { if(len <= dup) return len; int index = dup; for(int i=dup;i<len;i++) { if(A[index-dup] != A[i]) { A[index++] = A[i]; } } return index; } int main() { int A[] = {1,1,1,2,2,3,4,4,4}; std::cout << removeDuplicate(A,9,1) << " "; std::cout << removeDuplicate(A,9,2) << " "; std::cout << removeDuplicate(A,9,3) << " "; return 0; }
/******************************************* binary_search to find a target from a Rotated Array len: the length of A[] ********************************************/ int binary_search(int A[],int len,int target) { if(len <= 0) return -1; int first = 0; int last = len; int mid; while(first != last) { mid = (first + last)/2; if(A[mid] == target) return mid; if(A[first] <= A[mid]) { if(A[first] <= target && target < A[mid]) last = mid; else first = mid + 1; } else { if(A[mid] < target && target <= A[last - 1]) first = mid + 1; else last = mid; } } return -1; } int main() { int A[] = {7,8,9,1,2,3,4,5,6}; for(int i=1;i<10;i++) { std::cout << binary_search(A,9,i) << " "; } return 0; }