leetcode刷题(五)

本文深入解析链表的旋转与翻转算法,展示如何高效处理数据结构问题。同时,介绍了一种快速查找mxn矩阵中目标值的方法,利用矩阵特性将其转化为一维有序数组进行二分查找,提升搜索效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.给定一个链表,旋转链表,将链表每个节点向右移动 个位置,其中 是非负数。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
 ListNode* rotateRight(ListNode* head, int k) {
        ListNode *pst = head;
        ListNode *last = NULL;
        int count = 0;
        while(pst != NULL){
            ++count;
            last = pst;
            pst = pst->next; 
        }
        if(count == 0){
            return head;
        }
        int actual = k % count;
        last -> next = head;
        pst = head;
        for(int i = 0;i < count - actual - 1;++i){
            pst = pst->next;
        }
        head = pst->next;
        pst->next = NULL;
        return head;
    }
};

2.链表翻转  

struct ListNode {
	ListNode(int data) : next(NULL), val(data){}
	ListNode *next;
	int val;
};

 ListNode * ReverseList(ListNode *head)
{
	 ListNode *last = NULL, *next;
	 ListNode *cursor = head;
	 while (cursor->next != NULL)
	 {
		 next = cursor->next;
		 cursor->next = last;
		 last = cursor;
		 cursor = next;
	} 
	 cursor->next = last;
	 return cursor;
}

3.编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:

每行中的整数从左到右按升序排列。
每行的第一个整数大于前一行的最后一个整数。

//将二维矩阵看成是一个一维的有序数组
//进行下标的转换
 bool binaryfind(std::vector<std::vector<int>> &line, int left, int right, int target)
 {
	 while (left <= right)
	 {
		 int mid = (left + right) / 2;
		 int i = mid / line[0].size();
		 int j = mid - line[0].size() * i;

		 if (line[i][j] == target)
			 return true;

		 if (line[i][j] > target)
			 right = mid - 1;
		 else
			 left = mid + 1;
	 }
	 return false;
 }

 bool searchMatrix(std::vector<std::vector<int>>& matrix, int target) {

     if(matrix.empty())
         return false;
	 return binaryfind(matrix, 0, matrix.size() * matrix[0].size() - 1, target);
 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值