1.给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
/**
* 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);
}