整数数组中1)找出两个数差的绝对值的最小值 2)三个数和的绝对值的最小值

 

package com.java.ly2011.July;

public class ArraySumAndMinus {
 public static void main(String[] args) {
  int[] a = new int[]{1,43,12,54,423,654,231,3,51,765,32};
  System.out.println(twoIntegerReduceAbsMin(a));
  
  int[] b = new int[]{-8,-6,-4,-2,-1,+19,+187,+170};
  System.out.println(threeIntegerSumMinAbsValue(b));
  
 }
 
 /**
  * 找出数组中 两个数的差的绝对值最小  找出这个最小值
  * 先排序,然后遍历数组,相邻两个元素的差 才可能是这个最小值
  * @param a
  * @return
  */
 public static int twoIntegerReduceAbsMin(int[] a){
  quickSort(a, 0, a.length-1);
  int min = Integer.MAX_VALUE;
  for(int i = 1; i<=a.length-1;i++){
   int reduceValue = a[i]-a[i-1];
   if(reduceValue<min)
    min = reduceValue;
  }
  
  return min;
 }
 
 /**
  * 找出a数组中三个数和 绝对值最小,找出这个最小值
  * @param a
  * @return
  */
 public static int threeIntegerSumMinAbsValue(int[] a){
  
  quickSort(a, 0, a.length-1);
  
  int resultMin = Integer.MAX_VALUE;
  for(int i = 0;i<a.length;i++){
  
   int first = i;
   
   
   int begin = 0;
   int end = a.length-1;
   int sumtemp = Integer.MAX_VALUE;
   if(begin==i)
    begin++;
   if(end==i)
    end--;
   
   while(begin<end){
    
    int loopSum = a[first]+ a[begin] + a[end];
    if( loopSum<0 ){
     loopSum=-loopSum;
     begin++;
     if(begin==i)
      begin++;
    }
    else{
     end--;
     if(end==i)
      end--;
    }
    if(loopSum<sumtemp){
     sumtemp = loopSum;
     if(loopSum==0)
      break;
    }
   }
   
   if(sumtemp<resultMin)
    resultMin = sumtemp;
   if(resultMin==0)
    break;
  
  }
  
  return resultMin;
 }
 
 /**
  * 快速排序主程序   升序排序  p为0,q为n-1则排数组全部
  * @param p  起始位置p    0
  * @param q  终止位置q    n-1
  * @param A  待排序数组A
  */
 private static void quickSort(int[] A,int begin,int end){
  
  if(begin>=end){
   return;
  }else{
   int part=partition(A,begin, end);//能进入partition的都满足begin<end这个条件
   quickSort(A, begin, part-1);
   quickSort(A, part+1, end);
  }
  
 }
   
 /**
  * 被划分的数组时A[m,p-1]
  * @param m  起始位置
  * @param p  终止位置 
  * @param A  数组A
  * 返回 交换的位置
  */
 private static int  partition(int[] A,int m,int p){
  
  int leftbound = m+1;
  int rightbound = p;
  
  int begin=leftbound;
  int end=rightbound;
  int v=A[m];
  
  while(begin<=end){
   //判断界限写在前面,这样如果越界就会短路,不执行后面的A[begin]及A[end]了,以防止数组越界抛出outofbound异常
   for( ; begin<=rightbound && A[begin]<=v ; begin++);
   for( ; end>=leftbound && A[end]>v ; end--);
   if(begin<end) {
    int temp=A[begin];
    A[begin]=A[end];
    A[end]=temp;
   }

  }
  //交换A[m](划分的标准数) 及  A[end]
  A[m]=A[end];
  A[end]=v;
  return end;
  
 }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值