Same Element in Two Sorted Array
题目:
给两个排好序的没重复array要求返回两个array中共有的element。followup是有重复怎么做。
解题思路:
这道题的思路就是双指针。
代码:
给两个排好序的没重复array要求返回两个array中共有的element。followup是有重复怎么做。
解题思路:
这道题的思路就是双指针。
代码:
public List<Integer> findSameElement(int[] nums1, int[] nums2){ List<Integer> rst = new ArrayList<>(); int j = 0; for(int i = 0; i <= nums1.length - 1; i++){ while(j <= nums2.length - 1 && nums2[j] < nums1[i]){ j++; } if(j <= nums2.length - 1 && nums2[j] == nums1[i]){ rst.add(nums2[j]); j++; } } return rst; } public static void main(String[] args){ SameElementinTwoSortedArray sameElementinTwoSortedArray = new SameElementinTwoSortedArray(); int[] nums1 = {1, 2, 2, 4, 5, 7, 9}; int[] nums2 = {2, 2, 3, 6, 7}; List<Integer> rst = sameElementinTwoSortedArray.findSameElement(nums1, nums2); System.out.println(rst); }

Comments
Post a Comment