📌  相关文章
📜  两个列表的公共元素的最小索引和

📅  最后修改于: 2021-10-27 09:17:28             🧑  作者: Mango

Ram 和 Shyam 想选择一个网站来学习编程,他们都有一个由字符串表示的最喜欢的网站列表。
你需要帮助他们用最少的索引和找出他们的共同兴趣。如果答案之间有选择关系,请打印所有答案,没有顺序要求。假设总是存在一个答案。

例子:

Input : ["GeeksforGeeks", "Udemy", "Coursera", "edX"]
        ["Codecademy", "Khan Academy", "GeeksforGeeks"]
Output : "GeeksforGeeks"
Explanation : GeeksforGeeks is the only common website 
              in two lists

Input : ["Udemy", "GeeksforGeeks", "Coursera", "edX"]
        ["GeeksforGeeks", "Udemy", "Khan Academy", "Udacity"]
Output : "GeeksforGeeks" "Udemy"
Explanation : There are two common websites and index sum
              of both is same.

天真方法:

这个想法是尝试从 0 到大小总和的所有索引总和。对于每个总和,检查是否有给定总和的对。一旦我们找到一对或多对,我们就打印它们并返回。

C++
#include 
using namespace std;
 
// Function to print common strings with minimum index sum
void find(vector list1, vector list2)
{
    vector res; // resultant list
    int max_possible_sum = list1.size() + list2.size() - 2;
 
    // iterating over sum in ascending order
    for (int sum = 0; sum <= max_possible_sum ; sum++)
    {
        // iterating over one list and check index
        // (Corresponding to given sum) in other list
        for (int i = 0; i <= sum; i++)
         
            // put common strings in resultant list 
            if (i < list1.size() &&
                (sum - i) < list2.size() &&
                list1[i] == list2[sum - i])
                res.push_back(list1[i]);        
 
        // if common string found then break as we are
        // considering index sums in increasing order.
        if (res.size() > 0)
            break;
    }
 
    // print the resultant list
    for (int i = 0; i < res.size(); i++)
        cout << res[i] << " ";
}
 
// Driver code
int main()
{
    // Creating list1
    vector list1;
    list1.push_back("GeeksforGeeks");
    list1.push_back("Udemy");
    list1.push_back("Coursera");
    list1.push_back("edX");
 
    // Creating list2
    vector list2;
    list2.push_back("Codecademy");
    list2.push_back("Khan Academy");
    list2.push_back("GeeksforGeeks");
 
    find(list1, list2);
    return 0;
}


Java
import java.util.*;
 
class GFG
{
 
// Function to print common Strings with minimum index sum
static void find(Vector list1, Vector list2)
{
    Vector res = new Vector<>(); // resultant list
    int max_possible_sum = list1.size() + list2.size() - 2;
 
    // iterating over sum in ascending order
    for (int sum = 0; sum <= max_possible_sum ; sum++)
    {
        // iterating over one list and check index
        // (Corresponding to given sum) in other list
        for (int i = 0; i <= sum; i++)
         
            // put common Strings in resultant list
            if (i < list1.size() &&
                (sum - i) < list2.size() &&
                list1.get(i) == list2.get(sum - i))
                res.add(list1.get(i));        
 
        // if common String found then break as we are
        // considering index sums in increasing order.
        if (res.size() > 0)
            break;
    }
 
    // print the resultant list
    for (int i = 0; i < res.size(); i++)
        System.out.print(res.get(i)+" ");
}
 
// Driver code
public static void main(String[] args)
{
    // Creating list1
    Vector list1 = new Vector<>();
    list1.add("GeeksforGeeks");
    list1.add("Udemy");
    list1.add("Coursera");
    list1.add("edX");
 
    // Creating list2
    Vector list2= new Vector<>();
    list2.add("Codecademy");
    list2.add("Khan Academy");
    list2.add("GeeksforGeeks");
 
    find(list1, list2);
 
}
}
 
// This code contributed by Rajput-Ji


Python3
# Function to print common strings
# with minimum index sum
def find(list1, list2):
    res = [] # resultant list
    max_possible_sum = len(list1) + len(list2) - 2
 
    # iterating over sum in ascending order
    for sum in range(max_possible_sum + 1):
         
        # iterating over one list and check index
        # (Corresponding to given sum) in other list
        for i in range(sum + 1):
 
            # put common strings in resultant list
            if (i < len(list1) and
               (sum - i) < len(list2) and
                list1[i] == list2[sum - i]):
                res.append(list1[i])
 
        # if common string found then break as we are
        # considering index sums in increasing order.
        if (len(res) > 0):
            break
 
    # print the resultant list
    for i in range(len(res)):
        print(res[i], end = " ")
 
# Driver code
 
# Creating list1
list1 = []
list1.append("GeeksforGeeks")
list1.append("Udemy")
list1.append("Coursera")
list1.append("edX")
 
# Creating list2
list2 = []
list2.append("Codecademy")
list2.append("Khan Academy")
list2.append("GeeksforGeeks")
 
find(list1, list2)
 
# This code is contributed by Mohit Kumar


C#
using System;
using System.Collections.Generic;
 
class GFG
{
 
// Function to print common Strings with minimum index sum
static void find(List list1, List list2)
{
    List res = new List(); // resultant list
    int max_possible_sum = list1.Count + list2.Count - 2;
 
    // iterating over sum in ascending order
    for (int sum = 0; sum <= max_possible_sum ; sum++)
    {
        // iterating over one list and check index
        // (Corresponding to given sum) in other list
        for (int i = 0; i <= sum; i++)
         
            // put common Strings in resultant list
            if (i < list1.Count &&
                (sum - i) < list2.Count &&
                list1[i] == list2[sum - i])
                res.Add(list1[i]);
 
        // if common String found then break as we are
        // considering index sums in increasing order.
        if (res.Count > 0)
            break;
    }
 
    // print the resultant list
    for (int i = 0; i < res.Count; i++)
        Console.Write(res[i]+" ");
}
 
// Driver code
public static void Main(String[] args)
{
    // Creating list1
    List list1 = new List();
    list1.Add("GeeksforGeeks");
    list1.Add("Udemy");
    list1.Add("Coursera");
    list1.Add("edX");
 
    // Creating list2
    List list2= new List();
    list2.Add("Codecademy");
    list2.Add("Khan Academy");
    list2.Add("GeeksforGeeks");
 
    find(list1, list2);
 
}
}
 
// This code is contributed by 29AjayKumar


Javascript


C++
// Hashing based C++ program to find common elements
// with minimum index sum.
#include 
using namespace std;
 
// Function to print common strings with minimum index sum
void find(vector list1, vector list2)
{
    // mapping strings to their indices
    unordered_map map;
    for (int i = 0; i < list1.size(); i++)
        map[list1[i]] = i;
 
    vector res; // resultant list
 
    int minsum = INT_MAX;
    for (int j = 0; j < list2.size(); j++)
    {
        if (map.count(list2[j]))
        {
            // If current sum is smaller than minsum
            int sum = j + map[list2[j]];
            if (sum < minsum)
            {
                minsum = sum;
                res.clear();
                res.push_back(list2[j]);
            }
 
            // if index sum is same then put this
            // string in resultant list as well 
            else if (sum == minsum)
                res.push_back(list2[j]);
        }
    }
 
    // Print result
    for (int i = 0; i < res.size(); i++)
        cout << res[i] << " ";
}
 
// Driver code
int main()
{
    // Creating list1
    vector list1;
    list1.push_back("GeeksforGeeks");
    list1.push_back("Udemy");
    list1.push_back("Coursera");
    list1.push_back("edX");
 
    // Creating list2
    vector list2;
    list2.push_back("Codecademy");
    list2.push_back("Khan Academy");
    list2.push_back("GeeksforGeeks");
 
    find(list1, list2);
    return 0;
}


Java
// Hashing based Java program to find common elements
// with minimum index sum.
import java.util.*;
 
class GFG
{
 
    // Function to print common Strings with minimum index sum
    static void find(Vector list1, Vector list2)
    {
        // mapping Strings to their indices
        Map map = new HashMap<>();
        for (int i = 0; i < list1.size(); i++)
            map.put(list1.get(i), i);
 
        Vector res = new Vector(); // resultant list
 
        int minsum = Integer.MAX_VALUE;
        for (int j = 0; j < list2.size(); j++)
        {
            if (map.containsKey(list2.get(j)))
            {
                // If current sum is smaller than minsum
                int sum = j + map.get(list2.get(j));
                if (sum < minsum)
                {
                    minsum = sum;
                    res.clear();
                    res.add(list2.get(j));
                }
 
                // if index sum is same then put this
                // String in resultant list as well
                else if (sum == minsum)
                    res.add(list2.get(j));
            }
        }
 
        // Print result
        for (int i = 0; i < res.size(); i++)
            System.out.print(res.get(i) + " ");
    }
 
    // Driver code
    public static void main(String[] args)
    {
        // Creating list1
        Vector list1 = new Vector();
        list1.add("GeeksforGeeks");
        list1.add("Udemy");
        list1.add("Coursera");
        list1.add("edX");
 
        // Creating list2
        Vector list2 = new Vector();
        list2.add("Codecademy");
        list2.add("Khan Academy");
        list2.add("GeeksforGeeks");
 
        find(list1, list2);
    }
}
 
// This code is contributed by PrinciRaj1992


Python3
# Hashing based Python3 program to find
# common elements with minimum index sum
import sys
 
# Function to print common strings
# with minimum index sum
def find(list1, list2):
     
    # Mapping strings to their indices
    Map = {}
    for i in range(len(list1)):
        Map[list1[i]] = i
         
    # Resultant list
    res = []
     
    minsum = sys.maxsize
     
    for j in range(len(list2)):
        if list2[j] in Map:
             
            # If current sum is smaller
            # than minsum
            Sum = j + Map[list2[j]]
             
            if (Sum < minsum):
                minsum = Sum
                res.clear()
                res.append(list2[j])
  
            # If index sum is same then put this 
            # string in resultant list as well  
            elif (Sum == minsum):
                res.append(list2[j])
  
    # Print result
    print(*res, sep = " ")
  
# Driver code
  
# Creating list1
list1 = []
list1.append("GeeksforGeeks")
list1.append("Udemy")
list1.append("Coursera")
list1.append("edX")
  
# Creating list2
list2 = []
list2.append("Codecademy")
list2.append("Khan Academy")
list2.append("GeeksforGeeks")
find(list1, list2)
  
# This code is contributed by avanitrachhadiya2155


C#
// Hashing based C# program to find common elements
// with minimum index sum.
using System;
using System.Collections.Generic;
 
class GFG
{
 
    // Function to print common Strings with minimum index sum
    static void find(List list1, List list2)
    {
        // mapping Strings to their indices
        Dictionary map = new Dictionary();
        for (int i = 0; i < list1.Count; i++)
            map.Add(list1[i], i);
 
        List res = new List(); // resultant list
 
        int minsum = int.MaxValue;
        for (int j = 0; j < list2.Count; j++)
        {
            if (map.ContainsKey(list2[j]))
            {
                // If current sum is smaller than minsum
                int sum = j + map[list2[j]];
                if (sum < minsum)
                {
                    minsum = sum;
                    res.Clear();
                    res.Add(list2[j]);
                }
 
                // if index sum is same then put this
                // String in resultant list as well
                else if (sum == minsum)
                    res.Add(list2[j]);
            }
        }
 
        // Print result
        for (int i = 0; i < res.Count; i++)
            Console.Write(res[i] + " ");
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        // Creating list1
        List list1 = new List();
        list1.Add("GeeksforGeeks");
        list1.Add("Udemy");
        list1.Add("Coursera");
        list1.Add("edX");
 
        // Creating list2
        List list2 = new List();
        list2.Add("Codecademy");
        list2.Add("Khan Academy");
        list2.Add("GeeksforGeeks");
 
        find(list1, list2);
    }
}
 
// This code is contributed by Rajput-Ji


Javascript


输出:

GeeksforGeeks

时间复杂度: O((l 1 +l 2 ) 2 *x),其中l 1和l 2分别是list1 和list2 的长度,x 指的是字符串长度。
辅助空间: O(l*x),其中 x 指的是结果列表的长度,l 是最大字的长度。

使用哈希:

  1. 遍历 list1 并为哈希表中 list1 的每个元素创建一个条目。
  2. 遍历 list2 并为每个元素检查相同的元素是否已作为映射中的键存在。如果是,则表示该元素存在于两个列表中。
  3. 找出两个列表中公共元素对应的索引总和。如果该总和小于目前获得的最小总和,则更新结果列表。
  4. 如果总和等于到目前为止获得的最小总和,则在结果列表中添加与 list2 中的元素相对应的额外条目。

C++

// Hashing based C++ program to find common elements
// with minimum index sum.
#include 
using namespace std;
 
// Function to print common strings with minimum index sum
void find(vector list1, vector list2)
{
    // mapping strings to their indices
    unordered_map map;
    for (int i = 0; i < list1.size(); i++)
        map[list1[i]] = i;
 
    vector res; // resultant list
 
    int minsum = INT_MAX;
    for (int j = 0; j < list2.size(); j++)
    {
        if (map.count(list2[j]))
        {
            // If current sum is smaller than minsum
            int sum = j + map[list2[j]];
            if (sum < minsum)
            {
                minsum = sum;
                res.clear();
                res.push_back(list2[j]);
            }
 
            // if index sum is same then put this
            // string in resultant list as well 
            else if (sum == minsum)
                res.push_back(list2[j]);
        }
    }
 
    // Print result
    for (int i = 0; i < res.size(); i++)
        cout << res[i] << " ";
}
 
// Driver code
int main()
{
    // Creating list1
    vector list1;
    list1.push_back("GeeksforGeeks");
    list1.push_back("Udemy");
    list1.push_back("Coursera");
    list1.push_back("edX");
 
    // Creating list2
    vector list2;
    list2.push_back("Codecademy");
    list2.push_back("Khan Academy");
    list2.push_back("GeeksforGeeks");
 
    find(list1, list2);
    return 0;
}

Java

// Hashing based Java program to find common elements
// with minimum index sum.
import java.util.*;
 
class GFG
{
 
    // Function to print common Strings with minimum index sum
    static void find(Vector list1, Vector list2)
    {
        // mapping Strings to their indices
        Map map = new HashMap<>();
        for (int i = 0; i < list1.size(); i++)
            map.put(list1.get(i), i);
 
        Vector res = new Vector(); // resultant list
 
        int minsum = Integer.MAX_VALUE;
        for (int j = 0; j < list2.size(); j++)
        {
            if (map.containsKey(list2.get(j)))
            {
                // If current sum is smaller than minsum
                int sum = j + map.get(list2.get(j));
                if (sum < minsum)
                {
                    minsum = sum;
                    res.clear();
                    res.add(list2.get(j));
                }
 
                // if index sum is same then put this
                // String in resultant list as well
                else if (sum == minsum)
                    res.add(list2.get(j));
            }
        }
 
        // Print result
        for (int i = 0; i < res.size(); i++)
            System.out.print(res.get(i) + " ");
    }
 
    // Driver code
    public static void main(String[] args)
    {
        // Creating list1
        Vector list1 = new Vector();
        list1.add("GeeksforGeeks");
        list1.add("Udemy");
        list1.add("Coursera");
        list1.add("edX");
 
        // Creating list2
        Vector list2 = new Vector();
        list2.add("Codecademy");
        list2.add("Khan Academy");
        list2.add("GeeksforGeeks");
 
        find(list1, list2);
    }
}
 
// This code is contributed by PrinciRaj1992

蟒蛇3

# Hashing based Python3 program to find
# common elements with minimum index sum
import sys
 
# Function to print common strings
# with minimum index sum
def find(list1, list2):
     
    # Mapping strings to their indices
    Map = {}
    for i in range(len(list1)):
        Map[list1[i]] = i
         
    # Resultant list
    res = []
     
    minsum = sys.maxsize
     
    for j in range(len(list2)):
        if list2[j] in Map:
             
            # If current sum is smaller
            # than minsum
            Sum = j + Map[list2[j]]
             
            if (Sum < minsum):
                minsum = Sum
                res.clear()
                res.append(list2[j])
  
            # If index sum is same then put this 
            # string in resultant list as well  
            elif (Sum == minsum):
                res.append(list2[j])
  
    # Print result
    print(*res, sep = " ")
  
# Driver code
  
# Creating list1
list1 = []
list1.append("GeeksforGeeks")
list1.append("Udemy")
list1.append("Coursera")
list1.append("edX")
  
# Creating list2
list2 = []
list2.append("Codecademy")
list2.append("Khan Academy")
list2.append("GeeksforGeeks")
find(list1, list2)
  
# This code is contributed by avanitrachhadiya2155

C#

// Hashing based C# program to find common elements
// with minimum index sum.
using System;
using System.Collections.Generic;
 
class GFG
{
 
    // Function to print common Strings with minimum index sum
    static void find(List list1, List list2)
    {
        // mapping Strings to their indices
        Dictionary map = new Dictionary();
        for (int i = 0; i < list1.Count; i++)
            map.Add(list1[i], i);
 
        List res = new List(); // resultant list
 
        int minsum = int.MaxValue;
        for (int j = 0; j < list2.Count; j++)
        {
            if (map.ContainsKey(list2[j]))
            {
                // If current sum is smaller than minsum
                int sum = j + map[list2[j]];
                if (sum < minsum)
                {
                    minsum = sum;
                    res.Clear();
                    res.Add(list2[j]);
                }
 
                // if index sum is same then put this
                // String in resultant list as well
                else if (sum == minsum)
                    res.Add(list2[j]);
            }
        }
 
        // Print result
        for (int i = 0; i < res.Count; i++)
            Console.Write(res[i] + " ");
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        // Creating list1
        List list1 = new List();
        list1.Add("GeeksforGeeks");
        list1.Add("Udemy");
        list1.Add("Coursera");
        list1.Add("edX");
 
        // Creating list2
        List list2 = new List();
        list2.Add("Codecademy");
        list2.Add("Khan Academy");
        list2.Add("GeeksforGeeks");
 
        find(list1, list2);
    }
}
 
// This code is contributed by Rajput-Ji

Javascript


输出:

GeeksforGeeks

时间复杂度: O(l 1 +l 2 ),其中l 1和l 2分别是list1 和list2 的长度。
辅助空间: O(l 1 *x),其中 x 是结果列表的长度,l 是最大字的长度。

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程