• 计算数组中有几对相反数


    package interview;
    
    import java.util.Arrays;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    
    /**
     * 
     * @author 
     * 计算数组中有几对相反数
     *
     */
    public class ListSort {
    
    	public static void main(String[] args) {
    		ListSort test = new ListSort();
            List<Integer> list = Arrays.asList(9,1,3,8,-10,7,-9,-2,-8,2);
            Context<Integer> contextMin= new Context<>(test.new MinComparatorList());
    //        Context<Integer> contextMax= new Context<>(test.new MaxComparatorList());
            
            List<Integer> listMin = contextMin.sortList(list);
    //        List<Integer> listMax = contextMax.sortList(list);
            Integer[] arrays = (Integer[]) listMin.toArray();
          
            System.out.println(getCount(arrays,getMidIndex(arrays)));
    		
    	}
    	
    	public static int getCount(Integer[] arrays,int mid) {
    		int count=0;
    		for(int i=0;i<mid;i++) {
    			for(int j=mid;j<arrays.length;j++) {
    				if(arrays[i]+arrays[j]==0) {
    					count++;
    				}
    			}
    		}
    		return count;
    	}
    	
    	public static int getMidIndex(Integer[] arrays) {
    		    int start = 0;
    	        int end =arrays.length-1;
    	        int mid  = 0;
    	        while(start<=end) {
    	        	mid = (end-start)/2+start;
    	        	if((mid>0 && arrays[mid]>0&& arrays[mid-1]<0)) {
    	        		return mid;
    	        	}else if(mid>0 &&arrays[mid]>0 && arrays[mid-1]>0) {
    	        		end = mid-1;
    	        	}else if(arrays[mid]<0 && arrays[mid+1]<0){
    	        		start=mid+1;
    	        	}
    	        	
    	        }
    	        return mid;
    	}
    	
    	/*
    	 * 策略模式
    	 */
    	 class MinComparatorList implements Comparator<Integer>{
    
    		@Override
    		public int compare(Integer o1, Integer o2) {
    			return o1>o2?1:-1;
    		}
    	}
    	 class MaxComparatorList implements Comparator<Integer>{
    
    		@Override
    		public int compare(Integer o1, Integer o2) {
    			return o1<o2?1:-1;
    		}
    		
    	}
    	public static class Context<T>{
    		private Comparator<T> comparator;
    		public Context(Comparator<T> comparator) {
    			this.comparator = comparator;
    		}
    
    		public List<T> sortList(List<T> list) {
    			Collections.sort(list,comparator);
    			return list;
    		}
    		
    		
    	}
    	
    }
    
  • 相关阅读:
    Akka源码分析-Akka Typed
    Akka源码分析-Persistence Query
    5位ID生成方案
    Akka源码分析-Akka-Streams-GraphStage
    akka监控框架设计
    Akka源码分析-Akka-Streams-Materializer(1)
    day30-2FileWriter用数组进行复制文件
    day30-1FileInputStream不用数组进行复制文件
    day30-1FileInputStream用数组进行复制文件
    day29-2在d盘创建文件夹aaa 里面有aaa.txt bbb.txt ddd.txt
  • 原文地址:https://www.cnblogs.com/QAZLIU/p/9371056.html
Copyright © 2020-2023  润新知