数据结构-数组
public class arrayRepeatNumber { public static void main(String[] args){ int[] num={2,3,1,0,2,5,3}; // int[] num={1,1,2,2,2,2,3,3,4}; quickSort(num,0, num.length-1); locate(num); } public static void quickSort(int[] num,int left,int right){ if(left<right){ int i=left,j=right,x=num[left]; while(i<j){ while(i<j&&num[j]>=x){ j--; } if(i<j){ num[i++]=num[j]; } while(i<j&&num[i]<x){ i++; } if(i<j){ num[j--]=num[i]; } } num[i]=x; quickSort(num,left,i-1); quickSort(num,i+1,right); } } public static void locate(int[] num){ int len= num.length; int point=0; int mark=1; while(point<len-1){ if(num[point]==num[point+mark]){ mark++; } else{ point=point+mark; mark=1; } if(mark==2){ System.out.println(num[point]); } } } }
public static void findRepeatNumber(int[] num) { //定义一个集合hashset Set<Integer> set = new HashSet<Integer>(); //定义重复的标记 int repeat = -1; //对数组进行遍历 for (int i=0;i<num.length;i++) { repeat=-1; //如果添加失败(set不能添加重复元素),说明有重复元素 if (!set.add(num[i])) { //重复标记=当前数字 repeat = num[i]; } if(repeat!=-1){ System.out.println(repeat); } } }
//数组下标法 public static int subscript(int[] num){ for(int i=0;i< num.length;i++){ while(num[i]!=i){ if(num[i]==num[num[i]]){ return num[i]; } int tmp=num[num[i]]; num[num[i]]=num[i]; num[i]=tmp; } } return -1; }
public class matrixSearch { public static boolean matrixSearch(int[][] matrix ,int rows, int columns,int number){ boolean found=false; if(matrix!=null&&matrix.length>=0&&rows>0&&columns>0){ int row=0; int column=columns-1; while(row<rows&&column>=0){ if(matrix[row][column]==number){ found=true; break; } else if(matrix[row][column]>number){//如果当前元素比目标大 column--;//左移寻找 } else{//如果当前元素比目标小 row++;//下移寻找 } } } return found; } public static void main(String[] args){ int[][] num={{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}}; System.out.println(matrixSearch(num,4,4,7)); } }