leetcode的经常被面试,此题应该是一个修改
问题:
以k个元素为一组,反转单向链表。比如:
输入: 1->2->3->4->5->6->7->8->null and k = 3
输出:3->2->1->6->5->4->8->7->null.
问题:
以k个元素为一组,反转单向链表。比如:
输入: 1->2->3->4->5->6->7->8->null and k = 3
输出:3->2->1->6->5->4->8->7->null.
#include <stdio.h>
#include <stdlib.h>
//link list node
struct node{
int data;
struct node* next;
};
//递归函数 函数整体是翻转链表前k个节点
//结束条件 到最后节点为NULL
//但链表需要链接 所以将后面翻转的节点的prev赋给前面翻转的最后一个节点的next
//前面翻转后的最后一个节点,就是未翻转前的第一个节点,head
struct node *reverse(struct node *head, int k)
{
struct node *current = head;
struct node *next = NULL;
struct node *prev = NULL;
int count = 0;
//判断了k ==0 k == 1 head == NULL
while(current != NULL && count < k){
next = current->next;
current->next = prev;
prev = current;
current = next;
count++;
}
if(next != NULL){
head->next = reverse(next,k);
}
return prev;
}
struct node *reverse_n(struct node *head, int k)
{
if(head == NULL || head->next == NULL || k <= 1)
return head;
struct node *current = head;
struct node *next = NULL;
struct node *prev = NULL;
//前一个翻转链表的最后一个节点
struct node *prev_tail = NULL;
//当前翻转链表的最后一个节点
struct node *tail = NULL;
int count = 0;
int i;
while(current != NULL){
i = 0;
tail = current;
prev = NULL;
while(current != NULL && i < k){
next = current->next;
current->next = prev;
prev = current;
current = next;
i++;
}
if(count == 0) {head = prev;count++;}
if(prev_tail != NULL){prev_tail->next = prev;}
prev_tail = tail;
}
return head;
}
void push(struct node **head_ref, int new_data)
{
struct node *new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(struct node *node)
{
while(node != NULL){
printf("%d ",node->data);
node = node->next;
}
}
int main(void)
{
struct node *head = NULL;
push(&head,8);
push(&head,7);
push(&head,6);
push(&head,5);
push(&head,4);
push(&head,3);
push(&head,2);
push(&head,1);
printf("\n given linked list \n");
printList(head);
head = reverse_n(head, 3);
printf("\n reversed linked list \n");
printList(head);
return(0);
}
1.two sum
自己写的通过了,后来又参照了github上代码,忘了地址了。。。
前面自己总结的,查找,最优应该是o(1),hash。如果数据有序一般查找是o(logn),以2为底数。排序的话最优应该是o(n)了,因为把数据都要看一遍。
一般面试题都有特定的条件,根据特定的条件来思考算法,如果不行就用常规的位,hash等,前后指针,多个指针。
这个题目明显是空间换时间,试了下两次循环的,超时了。题目也没说排序好了,所以另外可以先排序在找。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int,int> numbers;
vector<int> result;
for(int i = 0; i < nums.size(); ++i){
numbers[nums[i]] = i;
}
for(int i = 0; i < numbers.size(); ++i){
int gap = target - nums[i];
if(numbers.find(gap) != numbers.end() && numbers[gap] > i){
result.push_back(i+1);
result.push_back(numbers[gap] + 1);
return result;
}
}
return result;
}
};