leetcode first missing positive,覆盖区间
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.
关键是O(n)复杂度及常量运行空间。
采用交换法。
class Solution {
public:
int firstMissingPositive(int A[], int n) {
for(int i=0;i<n;)
{
if(A[i]>0&&A[i]<=n&&A[i]!=i+1&&A[A[i]-1]!=A[i])
{
swap(A[A[i]-1],A[i]);
}
else i++;
}
for(int i=0;i<n;i++)
{
if(A[i]!=i+1)
{
return i+1;
}
}
return n+1;
}
};
采用另外一种hash方法。某大牛想出来的:
- 第一遍扫描排除所有非正的数,将它们设为一个无关紧要的正数(n+2),因为n+2不可能是答案
- 第二遍扫描,将数组作为hash表来使用,用数的正负来表示一个数是否存在在A[]中。
当遇到A[i],而A[i]属于区间[1,n],就把A中位于此位置A[i] – 1的数置翻转为负数。 所以我们取一个A[i]的时候,要取它的abs,因为如果它是负数的话,通过步骤一之后,只可能是我们主动设置成负数的。 - 第三遍扫描,如果遇到一个A[i]是正数,说明i+1这个数没有出现在A[]中,只需要返回即可。
- 上一步没返回,说明1到n都在,那就返回n+1
class Solution {
public:
int firstMissingPositive(int A[], int n) {
if(n <= 0) return 1;
const int IMPOSSIBLE = n + 1;
for(int i = 0; i < n; ++i) {
if(A[i] <= 0) A[i] = IMPOSSIBLE;
}
for(int i=0; i < n; ++i) {
int val = abs(A[i]);
if(val <= n && A[val-1] > 0)
A[val-1] *= -1;
}
for(int i = 0; i<n; ++i) {
if(A[i] > 0) return i+1;
}
return n+1;
}
};
覆盖区间
Insert Interval
Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
You may assume that the intervals were initially sorted according to their start times.
Example 1:
Given intervals [1,3],[6,9], insert and merge [2,5] in as [1,5],[6,9].
Example 2:
Given [1,2],[3,5],[6,7],[8,10],[12,16], insert and merge [4,9] in as [1,2],[3,10],[12,16].
This is because the new interval [4,9] overlaps with [3,5],[6,7],[8,10].
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
vector<Interval> result;
vector<Interval>::iterator it;
bool flag=true;
for (it=intervals.begin();it!=intervals.end();it++)
{
if (it->end<newInterval.start)
{
result.push_back(*it);
continue;
}
if (it->start>newInterval.end)
{
if (flag)
{
result.push_back(newInterval);
flag=false;
}
result.push_back(*it);
continue;
}
newInterval.start=it->start<newInterval.start?it->start:newInterval.start;
newInterval.end=it->end>newInterval.end?it->end:newInterval.end;
}
if (flag)
{
result.push_back(newInterval);
}
return result;
}
};
浙公网安备 33010602011771号