1. 程式人生 > >Coursera Algorithms week2 基礎排序 Interview Questions: 1 Intersection of two sets

Coursera Algorithms week2 基礎排序 Interview Questions: 1 Intersection of two sets

number style arr div void length contain 簡單 oca

題目原文:

Given two arrays a[] and b[], each containing n distinct 2D points in the plane, design a subquadratic algorithm to count the number of points that are contained both in array a[] and array b[].

題目的目標就是計算重復point的個數,很簡單,代碼如下

 1 import java.awt.Point;
 2 import java.util.Arrays;
 3 import java.util.HashSet;
4 import java.util.Set; 5 6 import edu.princeton.cs.algs4.StdRandom; 7 8 public class PlanePoints { 9 private Set<Point> s = new HashSet<Point>(); 10 private int samePointsNum; 11 PlanePoints(int n,Point[] inputa, Point[] inputb){ 12 for(int i=0;i<n;i++){
13 s.add(inputa[i]); 14 s.add(inputb[i]); 15 } 16 samePointsNum = 2*n - s.size(); 17 } 18 19 public int samePointsNum(){ 20 return samePointsNum; 21 } 22 23 public static void main(String[] args){ 24 int n = 10;
25 Point[] a = new Point[n]; 26 Point[] b = new Point[n]; 27 System.out.println(a.length); 28 for(int i=0;i<n;i++){ 29 a[i] = new Point(); 30 a[i].setLocation(StdRandom.uniform(n), StdRandom.uniform(n)); 31 b[i] = new Point(); 32 b[i].setLocation(StdRandom.uniform(n), StdRandom.uniform(n)); 33 } 34 System.out.println(Arrays.toString(a)); 35 System.out.println(Arrays.toString(b)); 36 PlanePoints pp = new PlanePoints(n,a,b); 37 System.out.println(pp.samePointsNum); 38 } 39 }

Coursera Algorithms week2 基礎排序 Interview Questions: 1 Intersection of two sets