leetcode 41. First Missing Positive
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.
my Solution:
class Solution {
public:
int firstMissingPositive(vector<int>& nums) {
if(nums.size() <1)
return 1;
int i;
for(i=0;iwhile(nums[i] >0 && nums[i] <= nums.size()&&nums[nums[i] -1]!=nums[i])
swap(nums[nums[i] -1],nums[i]);
}
for(int i=0;iif(nums[i] != i+1)
return i+1;
return nums.size()+1;
}
};
leetcode 25. Reverse Nodes in k-Group
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
下面是我的代码,不太符合固定存储空间的要求,但是accept and beats 73% cpp submissions.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* rh = head;
ListNode* ch;
ListNode* nhead = new ListNode(0);
nhead->next = head;
stack<int> record;
int n;
while(rh!=NULL)
{
ch = rh;
n=0;
while(ch!=NULL)
{
if(n>=k)
break;
record.push(ch->val);
n++;ch = ch->next;
}
if(nbreak;
while(rh!=ch)
{
rh->val = record.top();
record.pop();
rh = rh->next;
}
}
return nhead->next;
}
};
最优代码,我是一时没想起来链表反转,不过他这个递归调用,也很大程度简化了代码
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k)
{
if(head==NULL || k==1) return head;
int count=0;
ListNode* curr=head, *prev=NULL,*next=NULL;
while(curr)
{
curr=curr->next;
count++;
}
if(count < k) return head;
curr = head;
int i=0;
while(curr && inext=curr->next;
curr->next=prev;
prev=curr;
curr=next;
i++;
}
head->next=reverseKGroup(curr,k);
return prev;
}
};
“`
class Solution {
public:
bool isvalid(int row,int col,int N,vector &record)//判断是否能够放置
{
for(int i=0;i> &result,vector &record,int N)//输出
{
ostringstream re;
vector temp;
for(int i=0;i> solveNQueens(int n) {
vector> result;
int row=0,col=0;
vector record(n,-10000);
while(row
};