轩辕互动-1.求三个整数中第二大的数2.整型数组的平衡点

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class ExoWeb {

	public static void main(String[] args) {
		ExoWeb ew=new ExoWeb();
		
		System.out.println(ew.findSecondIn3Item(2, 5, 3));
		
		int[][] aa={
				{1,1,1,1,2,1},
				{1, 1, 0, 0, 1, 1},
				{1,2,0,2,1},
				{1,-1,1},
				{1,8,7,8,25,4,49,30,23},
				{1, 3, 5, 7, 8, 25, 4, 20},
		};
		for(int[] each:aa){
			System.out.print(Arrays.toString(each)+",balance points=");
			List<Integer> points=ew.findBalancePoint(each);
			for(int i:points){
				System.out.print(i+",");
			}
			System.out.println();
		}
	}

	/*
	 * find the mid item in THREE integers
	 */
	public int findSecondIn3Item(int a,int b,int c){
		//could this  be faster than sorting?
		int max=(a>b?a:b)>c?(a>b?a:b):c;
		int min=(a<b?a:b)<c?(a<b?a:b):c;
		int mid=a^b^c^max^min;	//equals to a+b+c-max-min
		/*
		int[] x=new int[3];
		x[0]=a;
		x[1]=b;
		x[2]=c;
		for(int i=0;i<x.length;i++){
			for(int j=0;j<x.length-i-1;j++){
				if(x[j]>x[j+1]){
					int temp=x[j];
					x[j]=x[j+1];
					x[j+1]=temp;
				}
			}
		}
		int mid=x[1];
		*/
	
		return mid;
	}
	
	/*
	 * 平衡点:比如int[] numbers = {1,3,5,7,8,25,4,20}; 25前面的总和为24,25后面的总和也是24,25这个点就是平衡点;
	 * 假如一个数组中的元素,其前面的部分等于后面的部分,那么这个点的位序就是平衡点 
	 * 要求1:返回任何一个平衡点
	 * 要求2:要求输入的数组可能是GB级
	 * solution to 1. use List<Integer>
	 * solution to 2. i cannot figure out a elegant solution. GB,,so you just cann't sum all the data in array
	 */
	public List<Integer> findBalancePoint(int[] a){
		List<Integer> points=new ArrayList<Integer>();
		int total=0;
		int firstSum=0;
		for(int i=0,len=a.length;i<len;i++){//若输入的数组是GB级,全部数组求和不可取
			total+=a[i];
		}
		for(int i=0,len=a.length;i<len;i++){
			if(firstSum==total-a[i]-firstSum){
				points.add(a[i]);
			}
			firstSum+=a[i];
		}
		return points;
	}
}

你可能感兴趣的:(数组)