计算数组中有几对相反数
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; } } }