算法学习14-在行列都排好序的矩阵中找数&&打印两个链表的公共部分

算法学习14-在行列都排好序的矩阵中找数&&打印两个链表的公共部分

在行列都排好序的矩阵中找数

【题目】

给定一个有N*M的整型矩阵matrix和一个整数K,matrix的每一行和每一
列都是排好序的。实现一个函数,判断K是否在matrix中。
例如:
0 1 2 5
2 3 4 7
4 4 4 8
5 7 7 9
如果K为7,返回true;如果K为6,返回false。
【要求】
时间复杂度为O(N+M),额外空间复杂度为O(1)。

算法思路

如果等于k,返回true表示已经找到
如果比k大,因为矩阵每一列都是排好序,所以在当前数所在的列中,处于当前数下方的数都比k大,则没有必要继续在第col列上寻找,令col = col- 1,重复步骤
如果比k小,因为矩阵每一列都是排好序,所以在当前数所在的行中,处于当前数左方的数都比k小,则没有必要继续在第row行上寻找,令row = row + 1,重复步骤

算法代码:

<isContanin.h>

#include<iostream>
#include<vector>
using namespace std; 

bool isContanin(vector<vector<int> >& matrix, int k){
	int row = 0;
    int col = matrix[0].size() - 1;
    while(row < matrix.size() && col > -1)
    {
       	if(matrix[row][col] == k)
            return true;
       	else if(matrix[row][col] > k)
            --col;
        else
            ++row;
    }
    return false;
};

<isContanin.cpp>

#include <iostream>
#include <vector>
#include"isContanin.h"
using namespace std;

int main()
{
    int a[] = {0, 1, 2, 5};
    vector<int> ivec(a, a + 4);
    vector<vector<int> > m;
    m.push_back(ivec);
    ivec[0] = 2;
    ivec[1] = 3;
    ivec[2] = 4;
    ivec[3] = 7;
    m.push_back(ivec);
    bool returnisContanin=isContanin(m, 7);
    cout <<returnisContanin<< endl;
}

打印两个链表的公共部分

【题目】

给定两个有序链表的头指针head1和head2,打印两个链表的公共部分。

算法思路:

定义两个指针,分别指向两个链表的头结点,比较value值,谁小移动谁;相等打印并同时移动,任何一个节点下一个节点是null,程序结束。

代码实现

<printComPart.h>

#include <iostream>

using namespace std;

struct Node
{
    int value;
    Node *next;
};

void printComPart(Node *head1,Node *head2)
{
    cout << "Common Part: " << endl;
    while(NULL != head1 && NULL != head2)
    {
        if(head1->value < head2->value)
            head1 = head1->next;
        else if(head1->value > head2->value)
            head2 = head2->next;
        else
        {
            cout << head1->value << " " ;
            head1 = head1->next;
            head2 = head2->next;
        }
    }
    cout << endl;
}

<printComPart.cpp>

#include <iostream>
#include"printComPart.h"
using namespace std;

int main()
{
    Node *head1 = NULL;
    Node *head2 = NULL;
    Node *ptr = NULL;
    
    for(int i =0;i<10;i++)
    {
        if(NULL == head1)
        {    
            head1 = new Node;
            head1->value = i;
            head1->next = NULL;
            ptr = head1;
            continue;
        }
        ptr->next = new Node;
        ptr = ptr->next;
        ptr->value = i;
        ptr->next = NULL;
    }
    for(int i =3;i<23;i++)
    {
        if(NULL == head2)
        {    
            head2 = new Node;
            head2->value = i;
            head2->next = NULL;
            ptr = head2;
            continue;
        }
        ptr->next = new Node;
        ptr = ptr->next;
        ptr->value = i;
        ptr->next = NULL;
    }
    printComPart(head1,head2);
    return 0;
}
发布了27 篇原创文章 · 获赞 1 · 访问量 1035

猜你喜欢

转载自blog.csdn.net/qq_45205390/article/details/104134526