9.1 You are given two sorted arrays, A and B, and A has a large enough buffer at the end to hold B. Write a method to merge B into A in sorted order.

A has enough buffer at the end to hold B, we can merge two arrays from end to start index, like merge two arrays in merge sort algorithm.

void mergeTwoArray(int A[],int m,int B[],int n){

int k=m+n-1;

m--;n--;

while(m>=0&&n>=0){

if(A[m]>=B[n])A[k--]=A[m--];

else A[k--]=B[n--];

}

while(m>=0)A[k--]=A[m--];

while(n>=0)A[k--]=B[n--];

}

9.2 Write a method to sort an array of strings so that all the anagrams are next to each other.

Based on basic sort function, we define a cmp function to decide how to sort. Here, we compare theirs anagrams' state.

int cmp(string s1,string s2){

sort(s1.begin(),s1.end());

sort(s2.begin(),s2.end());

if(s1<s2)return 1;

else return 0;

}

void sortStrings(vector<string> &strs){

sort(strs.begin(),strs.end(),cmp);

}

**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)

like binary search, we declare left/mid/right variables to represent current array part, because the array is rotated, we will have 8 states as following: k is the goal data.

k<a[mid],k<a[left],k<a[right], in this condition, right=mid-1 || left=mid+1, for we cannot make sure which part including rotated part.

k<a[mid],k<a[left],k>a[right], in this condition, left=mid+1;

k<a[mid],k>a[left],k<a[right], in this condition, right=mid-1;

k<a[mid],k>a[left],k>a[right], in this condition, right = mid-1;

k>a[mid],k<a[left],k<a[right], in this condition, left=mid+1;

k>a[mid],k<a[left],k>a[right], in this condition, right=mid-1;

k>a[mid],k>a[left],k<a[right], in this condition, left=mid+1;

k>a[mid],k>a[left],k>a[right], in this condition, left=mid+1 || right=mid-1;

int findIndex(int a[],int left,int right,int k){
if(left>right)return -1;
int mid=left+(right-left)/2;
if(k==a[mid])return mid;
else if(k==a[left])return left;
else if(k==a[right])return right;
else if(k<a[mid]){
if(k<a[left]){
if(k<a[right]){
int temp=findIndex(a,left,mid-1,k);
if(temp!=-1)return temp;
return findIndex(a,mid+1,right,k);
}else{
return findIndex(a,mid+1,right,k);
}
}else if(k>a[left]){
return findIndex(a,left,mid-1,k);
}
}else if(k>a[mid]){
if(k>right){
if(k>left){
int temp=findIndex(a,left,mid-1,k);
if(temp!=-1)return temp;
return findIndex(a,mid+1,right,k);
}else{
return findIndex(a,left,mid-1,k);
}
}else{
return findIndex(a,mid+1,right,k);
}
}
return -1;
}
int search(int A[], int n, int target) {
return findIndex(A,0,n-1,target);
}

Method2: not only compare target with a[left/mid/right], we compare a[left]/a[mid]/a[right] to decide which part has rotated part.

k<mid,left<mid,k<left, in this condition, left=mid+1

k<mid,left<mid,k>left, in this condition, right=mid-1

k<mid,left>mid, in this condition, right=mid-1

k>mid,left<mid, in this condition, left=mid+1

k>mid,left>mid,k>right, in this condition, right=mid-1

k>mid,left>mid,k<right, in this condition, left=mid+1

int search(int A[],int n,int target){

int left=0,right=n-1,mid;

while(left<=right){

mid=left+(right-left)/2;

if(A[mid]==target)return mid;

else if(target<A[mid]){

if(A[left]<=A[mid]){

if(target<A[left])left=mid+1;

else right=mid-1;

}else right=mid-1;

}else{

if(A[left]>A[mid]){

if(target<=A[right])left=mid+1;

else right=mid-1;

}else left=mid+1;

}

}

return -1;

}

9.4 If you have a 2 GB file with one string per line, which sorting algorithm would you use to sort the file and why?

external sort. Divide to N parts, sort each part, then N-way merge.

9.5 Given a sorted array of strings which is interspersed with empty strings, write a method to find the location of a given string.

Example: find “ball” in [“at”, “”, “”, “”, “ball”, “”, “”, “car”, “”, “”, “dad”, “”, “”] will return 4

Example: find “ballcar” in [“at”, “”, “”, “”, “”, “ball”, “car”, “”, “”, “dad”, “”, “”] will return -1

we do it based on binary search, first, we traverse the front part and the back part to make true left index and right index pointing to a no-empty string. Then we find mid index, if strs[mid]=="", we traverse mid to right
then to left to find the first no-empty string, this index is the mid index and do it like binary search.

int searchStrs(vector<string> strs,string target){

if(target==""||strs.size()==0)return -1;

int left=0,right=strs.size()-1,mid;

while(left<=right){

while(strs[left]==""&&left<right)left++;

while(strs[right]==""&&right>left)right--;

mid=left+(right-left)/2;

if(strs[left]==target)return left;

if(strs[right]==target)return right;

if(strs[mid]==""){

for(int i=mid+1;i<right;i++){if(strs[i]!="")break;}

if(i!=right)mid=i;

else{

for(int i=mid-1;i>left;i--){if(strs[i]!="")break;}

if(i!=left)mid=i

else return -1;

}

}

if(strs[mid]==target)return mid;

else if(strs[mid]<target)left=mid+1;

else if(strs[mid]>target)right=mid-1;

}

}

return -1;

}

9.6 Given a matrix in which each row and each column is sorted, write a method to find an element in it.

the matrix is sorted in rows and columns, let's assume it is a m*n matrix, we begin at matrix[0][n-1], if target< current, we move down, if target>current, we move left, if(target ==current) we find it, if we move out
of the matrix, the element isn't in it.

time complexity is O(n+m).

int rowAndColumn(vector<vector<int> > matrix,int target){

int m=matrix.size();if(m==0)return -1;

int n=matrix[0].size();if(n==0)return -1;

int x=0,y=n-1;

while(x<m&&y>=0){

if(matrix[x][y]==target)return x*n+y;

else if(matrix[x][y]>target)y--;

else if(matrix[x][y]<target)x++;

}

return -1;

}

9.7 A circus is designing a tower routine consisting of people standing atop one another’s shoulders. For practical and aesthetic reasons, each person must be both shorter and lighter than the person below him or her. Given the
heights and weights of each person in the circus, write a method to compute the largest possible number of people in such a tower.

EXAMPLE:

Input (ht, wt): (65, 100) (70, 150) (56, 90) (75, 190) (60, 95) (68, 110)

Output: The longest tower is length 6 and includes from top to bottom: (56, 90) (60,95) (65,100) (68,110) (70,150) (75,190)

we first sort all people by their height, then find the longest ascending sequence of their wight.

struct People{

int height;

int weight;

};

int cmp(People* p1,People* p2){

if(p1->height<p2->height)return 1;

else return 0;

}

int largestNum(vector<People*> peos){

if(peos.size()==0)return 0;

sort(peos.begin(),peos.end(),cmp);

int *f = new int[peos.size()];

int maxNum=0;

for(int i=0;i<peos.size();i++){

f[i]=1;

for(int j=0;j<i;j++){

if(peos[j]->weight<peos[i]->weight){

f[i]=max(f[i],f[j]+1);

}

}

maxNum=(maxNum>f[i]?maxNum:f[i]);

}

return maxNum;

}

CareerCup Chapter 9 Sorting and Searching的更多相关文章

  1. Algorithm in Practice - Sorting and Searching

    Algorithm in Practice Author: Zhong-Liang Xiang Date: Aug. 1st, 2017 不完整, 部分排序和查询算法, 需添加. Prerequisi ...

  2. 20162314 Experiment 3 - Sorting and Searching

    Experiment report of Besti course:<Program Design & Data Structures> Class: 1623 Student N ...

  3. Chp11: Sorting and Searching

    Common Sorting Algo: Bubble Sort: Runime: O(n2) average and worst case. Memory: O(1). void BubbleSor ...

  4. [Java in NetBeans] Lesson 15. Sorting and Searching.

    这个课程的参考视频和图片来自youtube. 主要学到的知识点有: Build in functions in java.util.Collections Need to implement a co ...

  5. Careercup | Chapter 1

    1.1 Implement an algorithm to determine if a string has all unique characters. What if you cannot us ...

  6. Careercup | Chapter 3

    3.1 Describe how you could use a single array to implement three stacks. Flexible Divisions的方案,当某个栈满 ...

  7. Careercup | Chapter 2

    链表的题里面,快慢指针.双指针用得很多. 2.1 Write code to remove duplicates from an unsorted linked list.FOLLOW UPHow w ...

  8. Careercup | Chapter 8

    8.2 Imagine you have a call center with three levels of employees: respondent, manager, and director ...

  9. Careercup | Chapter 7

    7.4 Write methods to implement the multiply, subtract, and divide operations for integers. Use only ...

随机推荐

  1. CriticalFinalizerObject的作用

    CriticalFinalizerObject 在从 CriticalFinalizerObject 类派生的类中,公共语言运行库 (CLR) 保证所有关键终止代码都有机会执行, 即使是在 CLR 强 ...

  2. 理解MySQL——架构与概念

    写在前面:最早接触的MySQL是在三年前,那时候MySQL还是4.x版本,很多功能都不支持,比如,存储过程,视图,触发器,更别说分布式事务等复杂特性了.但从5.0(2005年10月)开始,MySQL渐 ...

  3. JDBC连接Oracle数据库时出现的ORA-12505错误及解决办法

    转载至http://www.blogjava.net/itspy/archive/2007/12/20/169072.html Oracle 问题描述:今天使用jdbc连接oracle 10.2.0. ...

  4. iOS实现OAuth2.0中刷新access token并重新请求数据操作

    一.简要概述 OAuth2.0是OAuth协议的下一版本,时常用于移动客户端的开发,是一种比较安全的机制.在OAuth 2.0中,server将发行一个短有效期的access token和长生命期的r ...

  5. 武汉科技大学ACM:1008: 零起点学算法64——回型矩阵

    Problem Description 输出n*m的回型矩阵 Input 多组测试数据 每组输入2个整数 n和m(不大于20) Output 输出n*m的回型矩阵,要求左上角元素是1,(每个元素占2个 ...

  6. Oracle错误问题---- 《ora-12638:身份证明检索失败》

    使用客户端可以连接,但只有一个站点出现此问题,非常郁闷,网上查了一下,发现是用户认证问题,解决办法如下: 在ORACLE客户端目录下 NETWORK/ADMIN下的sqlnet.ora,使用记事本打开 ...

  7. Struts2+Spring4+Hibernate4整合超详细教程

    Struts2.Spring4.Hibernate4整合 超详细教程 Struts2.Spring4.Hibernate4整合实例-下载 项目目的: 整合使用最新版本的三大框架(即Struts2.Sp ...

  8. .net防止刷新重复提交(转)

    net 防止重复提交 微软防止重复提交方案,修改版 Code ; i < cookie.Values.Count; i++)                     log.Info(" ...

  9. 【Ecstore2.0】导出问题解决(未导出或导出文件为0字节)

    如果导出队列能成功执行(队列不执行看这里)但是并未生成文件,那么原因大部份可能是出在FTP上. ECSTORE2.0采用了PHP的FTP模块,所以先确认你的环境是否安装了FTP模块,如果没有,安装并在 ...

  10. po 和 mo 的互相转换

    反编译 mo 文件成 po 文件 msgunfmt test.mo -o test.po 编码 po 文件为 mo 文件 msgfmt -o test.mo test.po 记着备用.