Share My Java Two Pointers Solution


  • 0
    S
    public class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
            // Two Pointers
            Arrays.sort(nums1);
            Arrays.sort(nums2);
            int i = 0;
            int j = 0;
            int m = nums1.length;
            int n = nums2.length;
            List<Integer> list = new ArrayList<>();
            while (i < m && j < n) {
                if (nums1[i] == nums2[j]) {
                    list.add(nums1[i]);
                    while (++i < m && nums1[i] == nums1[i - 1]);
                    while (++j < n && nums2[j] == nums2[j - 1]);
                } else if (nums1[i] < nums2[j]) {
                    while (++i < m && nums1[i] == nums1[i - 1]);
                } else {
                    while (++j < n && nums2[j] == nums2[j - 1]);
                }
            }
            int[] res = new int[list.size()];
            for (int idx = 0; idx < list.size(); idx++) {
                res[idx] = list.get(idx);
            }
            return res;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.