* 搜狗2018春招后端编程笔试题一:
* 给定一个大小为n的正整数集合,要求找出这个数组中差值为k的数值对的个数。
* 数值对不能重复。
*
* 限制条件:
* 时间限制:C++ 1秒;JAVA 2秒
* 空间限制:忘了
*/
下面是我的答案,因为循环复杂度太高,超出时间限制,所以没有通过。但是算法是对的,就记录下。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
List<Integer> nums = new ArrayList<Integer>(); //n个正整数
Map<Integer,Integer> pair = new HashMap<Integer, Integer>();
for(int i = 0; i < n; i++){
nums.add(sc.nextInt());
}
int key = 0, value = 0;
for(int i = 0; i < n; i++){
key = nums.get(i);
int find1 = key + k;
int find2 = (key - k) > 0 ? key - k : 0;
for(int j = i; j < n; j++){
value = nums.get(j);
if(value == find1 || value == find2){
//放入HashMap中,key要比value小
if(key < value)
pair.put(key, value);
else
pair.put(value, key);
break;
}
}
}
System.out.println(pair.size());
}
}