public int threeSumClosest(int[] num, int target) {
    	assert num.length > 2:"the number of integers < 3!";
    	
    	if (num.length == 3)
    		return num[0]+num[1]+num[2];
    	
        Arrays.sort(num);    
        
        if (num[0] >= target) 
        	return num[0]+num[1]+num[2];
        
        if (num[num.length-1] <= target)
        	return num[num.length-1]+num[num.length-2]+num[num.length-3];
        
        int index = 0; // target at [num[pre],num[post]]
        while (num[index] < target){
        	index++;
        }
        
        int pre = index - 1;
        int post = index;
        int count = 0;
        int[] indexes = new int[]{-1,-1,-1};
        
        while (count < 3){
        	if (pre == 0){
        		for (int i = 0; i < indexes.length; i++) {
					if (indexes[i]==-1){
						indexes[i] = post;
						post++;
					}
				}
        		break;
        	}
        	
        	if (post == num.length){
        		for (int i = 0; i < indexes.length; i++) {
					if (indexes[i]==-1){
						indexes[i] = pre;
						pre--;
					}
        		}
        		break;
			}
        	
        	if (Math.abs(num[pre]-target) > Math.abs(num[post]-target)){
	        		indexes[count] = post;
					post ++;
	        		count ++;
        	} 
        	else {
        		indexes[count] = pre;
        		pre --;
        		count ++;
        	}
        }
        
        return num[indexes[0]]+num[indexes[1]]+num[indexes[2]];
    }