新浪笔试编程题三

来源:互联网 发布:网络暴力后果 编辑:程序博客网 时间:2024/06/08 05:49

一维点对问题

集合S中有直线上的n个点,n〉1

实现函数求出n个点之间的最短距离,并写出时间复杂度

   先使用排序算法将点的坐标排序,然后求相邻两点之间的最短距离即可,快排时间复杂度较低

public class Main3 {

public int partition(int[] nums, int begin, int end) {  
        int i = begin, j = end;  
        int x = nums[i];  
        while (i < j) {  
            while (i < j && x < nums[j])  
                --j;  
            if (i < j)  
                nums[i++] = nums[j];  
            while (i < j && nums[i] < x)  
                ++i;  
            if (i < j)  
                nums[j--] = nums[i];  
        }  
        nums[i] = x;  
        return i;  
    }  

public  void quickSort(int[] nums, int begin, int end) {  
   if (begin < end) {  
       int mid = partition(nums, begin, end);  
       quickSort(nums, begin, mid - 1);  
       quickSort(nums, mid + 1, end);  
   }  
}  
public int getMin(int[] array){
int temp = Integer.MAX_VALUE;
for(int i = 0;i<array.length-1;i++){
int re = Math.abs(array[i+1]-array[i]);
temp=temp<re?temp:re;

}
return temp;
}


public static void main(String[] args) {
Main3 m = new Main3();
int[] array = {5,8,9,4,1,3,6};
m.quickSort(array,0,array.length-1);
System.out.println(m.getMin(array));


}


}

0 0
原创粉丝点击