1.4.12

question:

Write a program that, given two sorted arrays of N int values, prints all elements that appear in both arrays, in sorted order. The running time of your program should be proportional to N in the worst case.

answer:

//注意上来连续多个元素相同的情况

import edu.princeton.cs.algs4.*;

public class SameValue
{
    public static int[] ans;
    public static int samevalue(int[] a, int[] b)
    {
        int len = a.length > b.length ? a.length : b.length;
        int t = 0;
        ans = new int[len];
        for(int i = 0, j = 0;i < a.length && j < b.length;)
        {
            if(a[i] == b[j])
            {
                if(t == 0)//t=0单独分析
                {

                    ans[t] = a[i];
                    i++;
                    j++;
                    t++;   
                }
                else if(a[i] != ans[t-1])//防止一个元素重复出现
                {

                    ans[t] = a[i];
                    i++;
                    j++;
                    t++;
                }
                else
                {
                    i++;
                    j++;
                }
            }
            else if(a[i] < b[j])
               i++; 
            else
                j++;
        }
        return t;
    }
    
    public static void main(String[] args)
    {
        int[] a = {1,1,1,2,2,2,2,4,5,6,6,6,6,6,6};
        int[] b = {1,1,1,2,2,2,2,5,7,8,8,9,9,9,10};
        int t = samevalue(a,b);
        for(int i = 0; i < t; i++)
        {
            StdOut.print(ans[i] + " ");
        }
        StdOut.println();
    }
}

猜你喜欢

转载自www.cnblogs.com/w-j-c/p/9129228.html
今日推荐