码迷,mamicode.com
首页 > 其他好文 > 详细

1.4.12

时间:2018-06-03 15:39:00      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:int   ase   static   多个   print   The   stdout   ring   ted   

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();
    }
}

 

1.4.12

标签:int   ase   static   多个   print   The   stdout   ring   ted   

原文地址:https://www.cnblogs.com/w-j-c/p/9129228.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!