标签:
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1]
, nums2 = [2, 2]
, return [2]
.
思路:
利用ArrayList的contains(Object o)方法进行交集的查询。
解法:
1 import java.util.ArrayList; 2 3 public class Solution 4 { 5 public int[] intersection(int[] nums1, int[] nums2) 6 { 7 ArrayList<Integer> list1 = new ArrayList<>(); 8 ArrayList<Integer> list2 = new ArrayList<>(); 9 ArrayList<Integer> list = new ArrayList<>(); 10 11 for(int i = 0; i < nums1.length; i++) 12 list1.add(nums1[i]); 13 for(int i = 0; i < nums2.length; i++) 14 list2.add(nums2[i]); 15 16 for(int i = 0; i < nums1.length; i++) 17 { 18 if(list2.contains(list1.get(i)) && !(list.contains(list1.get(i)))) 19 list.add(list1.get(i)) 20 } 21 22 int[] array = new int[list.size()]; 23 for(int i = 0; i < array.length; i++) 24 array[i] = list.get(i); 25 26 return array; 27 } 28 }
LeetCode 349 Intersection of Two Arrays
标签:
原文地址:http://www.cnblogs.com/wood-python/p/5732307.html