[Algorithm Series (5)]: Collection

table of Contents

1. Algorithm application

349. Intersection of two arrays

217. Duplicate elements exist

160. Intersecting Linked List

136. Numbers that only appear once

1042. Non-adjacent Flower Planting


The collection technology is mainly used to deal with the problem of repeated data in problem solving . Let’s take a look at the example of leetcode question bank directly to get a feel for it. . .

1. Algorithm application

349. Intersection of two arrays

  • Title description

Given two arrays, write a function to calculate their intersection.

示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2]
输出:[2]

示例 2:
输入:nums1 = [4,9,5], nums2 = [9,4,9,8,4]
输出:[9,4]
  • Problem-solving ideas

Directly use the structure of the collection

  • C++ code implementation
vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
    set<int> set1(nums1.begin(),nums1.end());
    set<int> set2(nums2.begin(),nums2.end());
 
    vector<int> res;
 
    for(auto i=set1.begin();i!=set1.end();++i){
        if(set2.find(*i)!=set2.end()){
            res.push_back(*i);
        }
    }
 
    return res;
}

217. Duplicate elements exist

  • Title description

Given an integer array, determine whether there are duplicate elements.

If any value appears at least twice in the array, the function returns true. If every element in the array is different, false is returned.

示例 1:
输入: [1,2,3,1]
输出: true

示例 2:
输入: [1,2,3,4]
输出: false
  • Problem-solving ideas

Through the collection method

  • C++ code implementation
 bool containsDuplicate(vector<int>& nums) {
	 map<int, int> dict;
	 for (int i = 0;i < nums.size();i++) {
		 if (dict.find(nums[i]) != dict.end()) {
			 return true;
		 }
		 else {
			 dict.insert(pair<int, int>(nums[i], 1));
		 }
	 }

	 return false;
 }

160. Intersecting Linked List

  • Title description

Write a program to find the starting node where two singly linked lists intersect.

Such as the following two linked lists :

The intersection starts at node c1.

Example 1:

输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
输入解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。从各自的表头开始算起,链表 A 为 
[4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 
个节点。
  • Problem-solving ideas

Through the collection method

  • C++ code implementation
 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
	 set<ListNode *> hash;
	 ListNode *tmp = headA;
	 while (tmp != NULL) {
		 hash.insert(tmp);
		 tmp = tmp->next;
	 }

	 tmp = headB;
	 while (tmp != NULL) {
		 if (hash.find(tmp) != hash.end()) {
			 return tmp;
		 }
		 tmp = tmp->next;
	 }

	 return NULL;
 }

136. Numbers that only appear once

  • Title description

Given an array of non-empty integers, except for an element that appears only once, every other element appears twice. Find the element that appears only once.

示例 1:
输入: [2,2,1]
输出: 1

示例 2:
输入: [4,1,2,1,2]
输出: 4
  • Problem-solving ideas

Through the collection method

  • C++ code implementation
int singleNumber(vector<int>& nums) {
	 set<int> sets;
	 for (int i = 0;i < nums.size();++i) {
		 if (sets.find(nums[i]) != sets.end()) {
			 sets.erase(nums[i]);
			 continue;
		 }
		 else {
			 sets.insert(nums[i]);
		 }
	 }

	 return *sets.begin();
 }

1042. Non-adjacent Flower Planting

  • Title description

There are N gardens, marked from 1 to N. In each garden, you plan to plant one of four kinds of flowers.

paths[i] = [x, y] describes the two-way path from garden x to garden y.

In addition, no garden has more than 3 paths to enter or leave.

You need to choose a type of flower for each garden so that the types of flowers in any two gardens connected by a path are different from each other.

Return the selected solutions as an array as the answer answer, where answer[i] is the type of flower planted in the (i+1)th garden. The types of flowers are represented by 1, 2, 3, and 4. Make sure that there is an answer.

示例 1:
输入:N = 3, paths = [[1,2],[2,3],[3,1]]
输出:[1,2,3]

示例 2:
输入:N = 4, paths = [[1,2],[3,4]]
输出:[1,2,1,2]

示例 3:
输入:N = 4, paths = [[1,2],[2,3],[3,4],[4,1],[1,3],[2,4]]
输出:[1,2,3,4]
  • Problem-solving ideas

Use dictionary + set to construct graph adjacency list.

  • C++ code implementation
bool judge(int j, vector<int>& res, vector<int>& vec)
    {
        for(int k=0;k<vec.size();k++)
        {
            if(res[vec[k]]==j)
            {
                return false;
            }
        }
        return true;
    }
 
    vector<int> gardenNoAdj(int N, vector<vector<int>>& paths) 
    {
        vector<int> res(N,0);
        int m=paths.size();
        vector<vector<int>> tmp(N);
        for(int i=0;i<m;i++)
        {
            tmp[paths[i][0]-1].push_back(paths[i][1]-1);
            tmp[paths[i][1]-1].push_back(paths[i][0]-1);
        }
        for(int i=0;i<N;i++)
        {
            for(int j=1;j<=4;j++)
            {
                if(judge(j,res,tmp[i]))
                {
                    res[i]=j;
                    break;
                }
            }
        }
        return res;
    }

Reference link:

Application of Set Technology in Solving Algorithmic Problems

Guess you like

Origin blog.csdn.net/wxplol/article/details/108461039