版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cuicanxingchen123456/article/details/84842846
1.数组中重复的数字(P39)
思路一是先排序,然后从头找,时间复杂度是O(nlogn)
思路二是hash表,将数组往hash表里存,如果已经有值表示找到了重复的值.时间复杂度是O(n)空间负载度是O(n).
思路三,从头到尾开始扫描,下标为i的数字m是不是等于i,如果是就继续扫,不是,再用m和下标i=m的数字n进行比较,如果n=m就找到了一个重复的数字,如果m和n不相同,就把m和n进行交换,把m放到属于它的位置,之后继续重复这个比较,交换的过程,直到发现一个重复的数字. 时间复杂度为O(n),空间复杂度为O(1)
public class demo1 {
static int[] m={2,3,1,0,2,5,3};
public static void main(String[] args) {
// TODO Auto-generated method stub
getrepeat(m);
}
public static boolean getrepeat(int[] m){
int k=0;
if(m.length==0){
System.exit(0);
}
for(int j=0;j<m.length;j++){
if(m[j]<0||m[j]>m.length-1){
System.exit(0);
}
}
for(int x=0;x<m.length;x++){
while(m[x]!=x){
if(m[x]==m[m[x]]){
return true;
}
int temp=m[x];
m[x]=m[temp];
m[temp]=temp;
}
}
return false;
}
}
2. 在上面的基础上,不修改数组找出重复的数字(P41)
思路:把从1~n的数字从中间的数字m分为两部分,前面一半为1~m,后面一半是m+1~n.如果1~m的数字的数目超过m,那么这一半的区间里一定包含重复的数字;否则,另一半m+1~n的区间里一定包含重复的数字.
长度为n的数组,时间复杂度是O(nlogn),空间复杂度为O(1).
public class demo2 {
static int[] num={2,3,5,4,3,2,6,7};
public static void main(String[] args){
int x=getdeplication(num, 7);
System.out.println(x);
}
public static int getdeplication(int[] num,int length){
if(num.length==0||length==0){
return -1;
}
int start=1;
int end=length-1;
while(end>=start){
int middle=((end-start)>>1)+start;
int count=countRange(num,length,start,end);
if(end==start){
if(count>1){
return start;
}else{
break;
}
}
if(count>(middle-start+1)){
end=middle;
}else{
start=middle+1;
}
}
return -1;
}
public static int countRange(int[] num,int length,int start,int end){
if(num==null){
return 0;
}
int count=0;
for(int i=0;i<length;i++){
if(num[i]>=start&&num[i]<=end){
++count;
}
}
System.out.println(count);
return count;
}
}
3. 二维数组中的查找(P44)
题目:在一个二维数组中,每一行都按照从左到右递增的顺序排序,每一列都按照从上到下递增的顺序排序.请完成一个函数,输入这样的一个二维数组和一个整数,判断数组中是否含有该整数.
1 2 8 9
2 4 9 12
4 7 10 13
6 8 11 15
思路:
从数组的右上角开始比对,如果大于该整数,则向左移一列,如果小于该整数,则向下移一行
public class demo3 {
static int[] num={1,2,8,9,2,4,9,12,4,7,10,13,6,8,11,15};
public static void main(String[] args) {
// TODO Auto-generated method stub
boolean f=Find(num,4,4,7);
System.out.println(f);
}
public static boolean Find(int[] num,int rows,int columns,int number){
boolean found=false;
if(num!=null&&rows>0&&columns>0){
int row=0;
int column=columns-1;
int value;
while(row<rows&&column>0){
value=num[row*columns+column];
if(num[row*columns+column]==number){
found=true;
return found;
}else if(num[row*columns+column]>number){
column--;
}else{
row++;
}
}
}
return found;
}
}