Here you can find the source of intersect2orderedList(List
Parameter | Description |
---|---|
s1 | shorter set |
s2 | longer set |
public static List<Integer> intersect2orderedList(List<Integer> s1, List<Integer> s2)
//package com.java2s; /******************************************************************************* * Copyright [2014] [Joarder Kamal]//w ww . j av a 2 s. c o m * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ import java.util.*; public class Main { /** * Computes the intersection of 2 integer ordered lists. * @param s1 shorter set * @param s2 longer set * @return intersection result */ public static List<Integer> intersect2orderedList(List<Integer> s1, List<Integer> s2) { if (s1.size() > s2.size()) return intersect2orderedList(s2, s1); List<Integer> res = new ArrayList<Integer>(); int pos1 = 0, pos2 = 0; while (pos1 < s1.size() && pos2 < s2.size()) { if (s1.get(pos1).equals(s2.get(pos2))) { res.add(s1.get(pos1)); pos1++; pos2++; } else { if (s1.get(pos1) < s2.get(pos2)) pos1++; else pos2++; } } return res; } }