随笔- 175  文章- 0  评论- 70 
2012年12月2日

Problem Statement

    

Cucumber Boy likes drawing pictures. Today, he plans to draw a picture using a very simple graphics editor.

 

The editor has the following functions:

  • The canvas is an infinite two-dimensional grid of pixels.
  • There are only two colors: black, and transparent. These are denoted 'B' and '.' (a period), respectively.
  • The editor has a clipboard that contains a rectangular picture.
  • The editor can take the picture in the clipboard and paste it onto any corresponding rectangle of the canvas. The user just has to select the pixel of the canvas where the upper left corner of the clipboard will be pasted.
  • When pasting the picture, the black pixels of the picture in the clipboard will overwrite their corresponding pixels on the canvas. The pixels that are transparent in the clipboard picture do not change the canvas.

 

At this moment, all pixels on the infinite canvas are transparent. Cucumber Boy has already stored a picture in the clipboard. You are given this picture as a vector <string> clipboard.

 

Cucumber Boy now wants to paste the clipboard picture onto the canvas exactly T times in a row.

For each i, when pasting the clipboard for the i-th time, he will choose the pixel (i,i) as the upper left corner of the pasted picture.

 

You are given the vector <string> clipboard and the int T. Return the number of black pixels on the canvas after all the pasting is finished.

Definition

    
Class: PastingPaintingDivTwo
Method: countColors
Parameters: vector <string>, int
Returns: long long
Method signature: long long countColors(vector <string> clipboard, int T)
(be sure your method is public)
    
 

Constraints

- clipboard will contain between 1 and 50 elements, inclusive.
- Each element of clipboard will contain between 1 and 50 characters, inclusive.
- Each element of clipboard will contain the same number of characters.
- Each character of each element of clipboard will be 'B' or '.'.
- T will be between 1 and 1,000,000,000, inclusive.

Examples

0)  
    
{
"..B",
"B..",
"BB."
}
3
Returns: 10

1)  
    
{
"B...",
"....",
"....",
"...B"
}
2
Returns: 4
 
2)  
    
{"BBB"}
10000
Returns: 30000
 
3)  
    
{"."}
1000000000
Returns: 0
 
4)  
    
{
"BB.",
".B."
}
100
Returns: 201
 
5)  
    
{
"..........B..........",
".........B.B.........",
"........B...B........",
".......B.....B.......",
"......B..B.B..B......",
".....B...B.B...B.....",
"....B...........B....",
"...B...B.....B...B...",
"..B.....BBBBBB....B..",
".B..........BB.....B.",
"BBBBBBBBBBBBBBBBBBBBB"
}
1000000000
Returns: 21000000071

Note that the answer may overflow a 32-bit integer variable.

 

This is the image of clipboard in this example.

只有在同一对角线的各自会影响到对方,所以按照对角线的方式来遍历每个格子,然后记录每个格子的开始和结束位置,之后做一下处理

 1 #include <vector>
 2 #include <string>
 3 using namespace std;
 4 
 5 class PastingPaintingDivTwo
 6 {
 7     public:
 8         long long calc(vector<string> clipboard, int T, int x, int y)
 9         {
10             long long sum = 0;
11             int endX = -1;
12             int endY = -1;
13             while(x < clipboard.size() && y < clipboard[0].size())
14             {
15                 if (clipboard[x][y] == 'B')
16                 {
17                     int endCurX = x + T - 1;
18                     int endCurY = y + T - 1;
19                     int startCurX = max(x, endX);
20                     int startCurY = max(y, endY);
21 
22                     sum += max(0, endCurX - startCurX + 1);
23 
24                     endX = max(endCurX + 1, endX);
25                     endY = max(endCurY + 1, endY);
26                 }
27 
28                 x++;
29                 y++;
30             }
31 
32             return sum;
33         }
34 
35         long long countColors(vector<string> clipboard, int T)
36         {
37             if (clipboard.size() == 0)
38                 return 0;
39 
40             long long sum = 0;
41             for(int i = 0; i < clipboard.size(); i++)
42             {
43                 sum += calc(clipboard, T, i, 0);
44             }
45 
46             for(int i = 1; i < clipboard[0].size(); i++)
47             {
48                 sum += calc(clipboard, T, 0, i);
49             }
50 
51             return sum;
52         }
53 };

 

posted @ 2012-12-02 14:45 remlostime 阅读(115) 评论(0) 编辑

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1
      / \
     2   3

 

Return 6.

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int calLen(TreeNode *root, int &len)
13     {
14         if (root == NULL)
15         {
16             len = 0;
17             return 0;
18         }
19         
20         if (root->left == NULL && root->right == NULL)
21         {
22             len = root->val;
23             return root->val;
24         }
25         
26         int leftPath, rightPath;
27         int leftLen;
28         if (root->left)
29             leftLen = calLen(root->left, leftPath);
30         else
31         {
32             leftLen = INT_MIN;
33             leftPath = 0;
34         }
35         
36         int rightLen;
37         if (root->right)
38             rightLen = calLen(root->right, rightPath);
39         else
40         {
41             rightLen = INT_MIN;
42             rightPath = 0;
43         }
44         
45         len = max(max(leftPath, rightPath) + root->val, root->val);
46         int maxLen = max(root->val, max(leftPath + rightPath + root->val, 
47             max(leftPath + root->val, rightPath + root->val)));
48         
49         return max(max(leftLen, rightLen), maxLen);
50     }
51     
52     int maxPathSum(TreeNode *root) {
53         // Start typing your C/C++ solution below
54         // DO NOT write int main() function
55         int len;
56         return calLen(root, len);
57     }
58 };
posted @ 2012-12-02 14:05 remlostime 阅读(714) 评论(0) 编辑
2012年11月29日

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int> &prices) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if (prices.size() == 0)
 7             return 0;
 8             
 9         vector<int> f1(prices.size());
10         vector<int> f2(prices.size());
11         
12         int minV = prices[0];
13         f1[0] = 0;
14         for(int i = 1; i < prices.size(); i++)
15         {
16             minV = min(minV, prices[i]);
17             f1[i] = max(f1[i-1], prices[i] - minV);
18         }
19         
20         int maxV = prices[prices.size()-1];
21         f2[f2.size()-1] = 0;
22         for(int i = prices.size() - 2; i >= 0; i--)
23         {
24             maxV = max(prices[i], maxV);
25             f2[i] = max(f2[i+1], maxV - prices[i]);
26         }
27         
28         int sum = 0;
29         for(int i = 0; i < prices.size(); i++)
30             sum = max(sum, f1[i] + f2[i]);
31             
32         return sum;
33     }
34 };
posted @ 2012-11-29 19:35 remlostime 阅读(653) 评论(0) 编辑
2012年11月27日

Implement wildcard pattern matching with support for '?' and '*'.

'?' Matches any single character.
'*' Matches any sequence of characters (including the empty sequence).

The matching should cover the entire input string (not partial).

The function prototype should be:
bool isMatch(const char *s, const char *p)

Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "*") → true
isMatch("aa", "a*") → true
isMatch("ab", "?*") → true
isMatch("aab", "c*a*b") → false

只能过小数据
 1 class Solution {
 2 public:
 3     bool isMatch(const char *s, const char *p) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         if (s == NULL && p == NULL)
 7             return true;
 8         else if (s == NULL || p == NULL)
 9             return false;
10             
11         if (*p == '?')
12         {
13             if (*s == '\0')
14                 return false;
15             else
16                 return isMatch(s + 1, p + 1);
17         }
18         else if (*p == '*')
19         {
20             while(*s != '\0')
21             {
22                 if (isMatch(s, p + 1))
23                     break;
24                 s++;
25             }
26             
27             if (*s != '\0')
28                 return true;
29             else
30                 return isMatch(s, p + 1);           
31         }
32         else
33         {
34             if (*s == *p)
35             {
36                 if (*s == '\0')
37                     return true;
38                 else
39                     return isMatch(s + 1, p + 1);
40             }
41             else
42                 return false;
43         }
44     }
45 };
posted @ 2012-11-27 10:23 remlostime 阅读(336) 评论(0) 编辑
2012年11月26日

The gray code is a binary numeral system where two successive values differ in only one bit.

Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.

For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:

00 - 0
01 - 1
11 - 3
10 - 2

Note:
For a given n, a gray code sequence is not uniquely defined.

For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.

For now, the judge is able to judge based on one instance of gray code sequence. Sorry about that.

 1 class Solution
 2 {
 3 public:
 4     /*
 5      * for reference: http://en.wikipedia.org/wiki/Gray_code.
 6      */
 7     vector<int> grayCode(int n)
 8     {
 9         vector<int> ret;
10         int size = 1 << n;
11         for(int i = 0; i < size; ++i)
12             ret.push_back((i >> 1)^i);
13         return ret;
14     }
15 };
posted @ 2012-11-26 21:44 remlostime 阅读(419) 评论(0) 编辑

Given a binary tree, flatten it to a linked list in-place.

For example,
Given

         1
        / \
       2   5
      / \   \
     3   4   6

 

The flattened tree should look like:

   1
    \
     2
      \
       3
        \
         4
          \
           5
            \
             6
Hints:

If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.

 

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 struct Node
11 {
12     TreeNode *head;
13     TreeNode *tail;
14     Node(){}
15     Node(TreeNode *h, TreeNode *t):head(h), tail(t){}
16 };
17 
18 class Solution {
19 public:
20     Node convert(TreeNode *root)
21     {
22         if (root == NULL)
23             return Node(NULL, NULL);
24             
25         Node leftNode = convert(root->left);
26         Node rightNode = convert(root->right);
27         
28         root->right = NULL;
29         root->left = NULL;
30         
31         if (leftNode.head)
32         {
33             root->right = leftNode.head;
34             leftNode.tail->right = rightNode.head;
35             
36         }
37         else
38         {
39             root->right = rightNode.head;
40         }
41         
42         TreeNode *tail;
43         if (rightNode.tail != NULL)
44             tail = rightNode.tail;
45         else if (leftNode.tail != NULL)
46             tail = leftNode.tail;
47         else
48             tail = root;
49             
50         return Node(root, tail);
51     }
52     
53     void flatten(TreeNode *root) {
54         // Start typing your C/C++ solution below
55         // DO NOT write int main() function
56         convert(root);
57     }
58 };

 

posted @ 2012-11-26 21:39 remlostime 阅读(514) 评论(0) 编辑

Divide two integers without using multiplication, division and mod operator.

 1 class Solution {
 2 private:
 3     long long f[100];
 4 public:
 5     int bsearch(long long a[], int left, int right, long long key)
 6     {
 7         if (left > right)
 8             return -1;
 9             
10         int mid = left + (right - left) / 2;
11         if (a[mid] == key)
12             return mid;
13         else if (a[mid] < key)
14         {
15             int pos = bsearch(a, mid + 1, right, key);
16             return pos == -1 ? mid : pos;
17         }
18         else
19         {
20             return bsearch(a, left, mid - 1, key);
21         }
22     }
23     
24     int divide(int dividend, int divisor) {
25         // Start typing your C/C++ solution below
26         // DO NOT write int main() function
27         int sign = dividend < 0 ? -1 : 1;
28         if (divisor < 0)
29             sign *= -1;
30         
31         long long div = dividend;
32         div = abs(div);
33         long long divisorL = divisor;
34         divisorL = abs(divisorL);
35         f[0] = divisorL;
36         int size = 1;
37         while(true)
38         {
39             if (f[size-1] >= div)
40                 break;
41             f[size] = f[size-1] + f[size-1];
42             size++;
43         }
44         
45         int num = 0;
46         long long sum = 0;
47         while(div > 0)
48         {
49             int pos = bsearch(f, 0, size - 1, div);
50             if (pos == -1)
51                 break;
52             div -= f[pos];
53             num += (1 << pos);
54         }
55                 
56         return num * sign;
57     }
58 };

 

 

posted @ 2012-11-26 21:23 remlostime 阅读(312) 评论(0) 编辑

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

 1 class Solution {
 2 public:
 3     char *strStr(char *haystack, char *needle) {
 4         // Start typing your C/C++ solution below
 5         // DO NOT write int main() function
 6         int hayLen = strlen(haystack);
 7         int needLen = strlen(needle);
 8         
 9         for(int i = 0; i <= hayLen - needLen; i++)
10         {
11             char *p = haystack + i;
12             char *q = needle;
13             while(*q != '\0')
14             {
15                 if (*p != *q)
16                     break;
17                 else
18                 {
19                     p++;
20                     q++;
21                 }
22             }
23             
24             if (*q == '\0')
25                 return haystack + i;            
26         }
27         
28         return NULL;
29     }
30 };
posted @ 2012-11-26 20:51 remlostime 阅读(196) 评论(0) 编辑

题目:二叉树的结点定义如下:

struct TreeNode

{

    int m_nvalue;

    TreeNode* m_pLeft;

    TreeNode* m_pRight;

};

输入二叉树中的两个结点,输出这两个结点在数中最低的共同父结点。

递归版本:空间O(1),时间O(n)

 

 1 struct Node
 2 {
 3     int val;
 4     Node *left;
 5     Node *right;
 6     Node():left(NULL), right(NULL){}
 7 };
 8 
 9 Node *findFather(Node *root, Node *node1, Node *node2, bool &node1Find, bool &node2Find)
10 {
11     if (root == NULL)
12         return NULL;
13 
14     bool leftNode1Find = false, leftNode2Find = false;
15     Node *leftNode = findFather(root->left, node1, node2, leftNode1Find, leftNode2Find);
16     if (leftNode != NULL)
17         return leftNode;
18 
19     bool rightNode1Find = false, rightNode2Find = false;
20     Node *rightNode = findFather(root->right, node1, node2, rightNode1Find, rightNode2Find);
21     if (rightNode != NULL)
22         return rightNode;
23 
24     node1Find = leftNode1Find || rightNode1Find;
25     node2Find = leftNode2Find || rightNode2Find;
26 
27     if (node1Find && node2Find)
28         return root;
29 
30     if (root == node1)
31         node1Find = true;
32 
33     if (root == node2)
34         node2Find = true;
35 
36     return NULL;
37 }

 

 

 

posted @ 2012-11-26 12:01 remlostime 阅读(111) 评论(0) 编辑
2012年11月25日

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Your goal is to reach the last index in the minimum number of jumps.

For example:
Given array A = [2,3,1,1,4]

The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)

 1 class Solution {
 2 private:
 3     int f[100000];
 4 public:
 5     int jump(int A[], int n) {
 6         // Start typing your C/C++ solution below
 7         // DO NOT write int main() function
 8         int maxPos = 0;
 9         f[0] = 0;
10         
11         for(int i = 0; i <= maxPos; i++)
12         {
13             int pos = i + A[i];
14             if (pos >= n)
15                 pos = n - 1;
16                 
17             if (pos > maxPos)
18             {
19                 for(int j = maxPos + 1; j <= pos; j++)
20                     f[j] = f[i] + 1;
21                 maxPos = pos; 
22             }
23             
24             if (maxPos == n - 1)
25                 return f[n-1];
26         }
27     }
28 };
posted @ 2012-11-25 20:53 remlostime 阅读(343) 评论(0) 编辑