peter
BAN USER- 0of 0 votes
Answersfind a cycle in the given array and return the length of a cycle
- peter in United States
for example, a[0] = 2, a[1] = 0, a[2] = 3, a[3] = 1, a[4] = 2, a[5] =4;
a[0]=2 -> a[2]=3 -> a[3]=1 -> a[1] =0 -> a[0]=2 ....
2->3-1>0->2->3->1->0->...
so return value should be 3.| Report Duplicate | Flag | PURGE
Samsung Software Engineer / Developer Algorithm - 0of 0 votes
AnswerWhat is K&R ?
- peter in United States
What is NP-complete? what does NP stand for?
How many bits of IPv4 and IPv6?| Report Duplicate | Flag | PURGE
NetApp Software Engineer / Developer Knowledge Based
int cycle(int a[], int num){
int count = 0;
//find a cycle
int *fast = a;
int *slow = a;
int *start = a;
do{
fast = &a[*fast];
fast = &a[*fast];
slow = &a[*slow];
}while(fast != slow);
//fix slow pointer, and move another pointer to run a cycle
start = slow;
do
{
start = &a[*start];
//slow = &a[*slow];
count++;
}while(start != slow);
printf("addess is same %d\n", *slow);
return count;
}
// took from leetcode
bool isValidBST(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
//if (root == NULL) return true;
return isValid(root, -1*INT_MAX, INT_MAX);
}
bool isValid(TreeNode *root, int min, int max){
if (root == NULL) return true;
if (root->val <= min || root->val >= max) return false;
if (root->left) {
if (root->val < root->left->val) return false;
}
if (root->right) {
if (root->val > root->right->val) return false;
}
bool ret = true;
ret &= isValid(root->left, min, root->val);
ret &= isValid(root->right, root->val, max);
}
string removeChar(string s, string t){
string result = "";
set<char> ss;
set<char>::iterator it;
int lengthT = t.size();
int lengthS = s.size();
if (lengthS < 1 || lengthT < 1) return s;
for(int i = 0; i < lengthT; i++){
if (t[i] >= 'A' && t[i] <= 'Z') t[i] = t[i] + 32;
ss.insert(t[i]);
}
for(int i = 0 ; i < lengthS; i++){
if(s[i] >= 'A' && s[i] <= 'Z') s[i] = s[i] + 32;
}
cout << "size of set: " << ss.size() << endl;
for(it = ss.begin(); it != ss.end(); it++){
cout << *it << endl;
}
for (int i =0; i < lengthS; i++){
it = ss.find(s[i]);
if (it == ss.end()) result = result + s[i];
}
return result;
}
right, the answer should be 4, not 3. I changed an example, but not the answer. sorry for making you confusing.
- peter January 14, 2014