Leetcode 217 存在重复元素
给定一个整数数组,判断是否存在重复元素。
如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。
// 实现原则:判断一个数组中是否存在重复元素,返回布尔值类型。 // 实现原理:对数组进行排序,之后进行判断是否存在重复元素。 public boolean containsDuplicate(int[] nums) { // 对数组进行排序o(nlogn) Arrays.sort(nums); boolean same=false; if(nums==null){ return true; } int i=0; while(i<nums.length){ if(i==nums.length-1){ break; } if(nums[i]==nums[i+1]){ return true; } i++; } return false; }
排序小结:
少看多练,才是正道。
public class 排序算法总结 { // 数组的定义 int []arr=new int[5]; int []arr1={1,2,3,4,5}; long []str2=new long[6]; String []strs=new String[5]; // 数组的操作:冒泡排序 public static void bubbleSort(int[] numbers){ int temp=0; // N个数要比较的轮次是N-1轮 for(int i=0;i<numbers.length-1;i++){ // 每一轮比较的次数是N-1-i for(int j=0;j<numbers.length-i-1;j++){ if(numbers[i]>numbers[j]){ temp=numbers[i]; numbers[i]=numbers[j]; numbers[j]=temp; } } } } public static int getMiddle(int[] numbers, int low,int high){ // low位置作为起始位置 int start=numbers[low]; while(low<high){ // 从后向前找到第一个小于low的数进行交换 while(low<high && numbers[high]>start){ high--; } numbers[low]=numbers[high]; // 从后向前找到第一个大于high的元素进行交换 while(low<high && numbers[low]<start){ low++; } numbers[high]=numbers[low]; // 中轴移动到队尾 numbers[low]=start; return low; } } public static void quickSort(int[] numbers,int low,int high){ if(low<high){ int middle=getMiddle(numbers, low, high); quickSort(numbers, low, middle-1); quickSort(numbers, middle+1, high); } } }