不重复打印排序数组中相加和为给定值的所有二元组
不重复打印排序数组中相加和为给定值的所有二元组
http://www.nowcoder.com/questionTerminal/1ff1a607c81748baa1823ffa687d74c4
双指针的应用
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String[] str = reader.readLine().split(" "); int n = Integer.parseInt(str[0]); int k = Integer.parseInt(str[1]); str = reader.readLine().split(" "); reader.close(); int[] arr = parse(str,n); int i = 0,j = n - 1; while(i < j){ if(arr[i] + arr[j] == k){ if(i==0 || arr[i] != arr[i - 1]) System.out.println(arr[i] + " " + arr[j]); i++; j--; } else if(arr[i] + arr[j] > k) j--; else i++; } } private static int[] parse(String[] str,int n){ int[] arr = new int[n]; for(int i = 0;i < n;i++){ arr[i] = Integer.parseInt(str[i]); } return arr; } }