码迷,mamicode.com
首页 > 编程语言 > 详细

计算数组中有几对相反数

时间:2018-07-26 15:10:17      阅读:302      评论:0      收藏:0      [点我收藏+]

标签:int   str   arrays   print   stat   list()   amp   ring   turn   

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;
		}
		
		
	}
	
}

 

计算数组中有几对相反数

标签:int   str   arrays   print   stat   list()   amp   ring   turn   

原文地址:https://www.cnblogs.com/QAZLIU/p/9371056.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!