标签:term solution lse style hat val ++ adr imp
question:
Write a program to determine the number pairs of values in an input file that are equal. If your first try is quadratic, think again and use Arrays.sort() to develop a linearithmic solution.
answer:
//题目要找有多少对相等的数,但是三个数相等怎么办,所以我是求的一共有多少组相等的数,我没有输入文件
import edu.princeton.cs.algs4.*; import java.util.Arrays; public class EqualValue { public static int equalvalue(int[] a) { Arrays.sort(a); int cnt = 0; int c = a[0]; int flag = 1;//防止重复判断一个数相等 for(int i = 1; i < a.length; i++) { if(a[i] == c)//相等 { if(flag != 0) { flag = 0; cnt++; } } else//不相等则换当前数为相等数来进行下一次判断 { flag = 1; c = a[i]; } } return cnt; } public static void main(String[] args) { int a[] = {1, 3, 4, 1, 2, 2, 4, 5, 1, 5}; int ans = equalvalue(a); StdOut.println(ans); } }
标签:term solution lse style hat val ++ adr imp
原文地址:https://www.cnblogs.com/w-j-c/p/9128261.html