-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfind_fixed_point.cpp
More file actions
73 lines (58 loc) · 1.56 KB
/
find_fixed_point.cpp
File metadata and controls
73 lines (58 loc) · 1.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//
// Created by Mayank Parasar on 2020-03-14.
//
/*
A fixed point in a list is where the value is equal to its index. So for example the list [-5, 1, 3, 4],
1 is a fixed point in the list since the index and value is the same. Find a fixed point (there can be many,
just return 1) in a sorted list of distinct elements, or return None if it doesn't exist.
Here is a starting point:
def find_fixed_point(nums):
# Fill this in.
print find_fixed_point([-5, 1, 3, 4])
# 1
*/
#include<iostream>
#include<vector>
using namespace std;
// this works with both sorted and unsorted
int brute_force(const vector<int>& vec) {
for(int ii = 0; ii < (int)vec.size(); ii++){
if(ii == vec[ii])
return (ii);
}
return (-1);
}
// optimization for sorted list of distinct elements,
int optimized_search(const vector<int>& vec) {
// assuming vector is sorted in acending order...
for(int ii = 0; ii < (int)vec.size(); ii++){
if(vec[ii] > ii) {
return -1; // short-circuit logic
}
else if (vec[ii] < ii) {
continue;
}
else if (vec[ii] == ii) {
return (ii);
}
}
return (-1);
}
int main() {
vector<int> vec = {-5, 1, 3, 4};
if(brute_force(vec) == -1) {
cout << "None";
}
else {
cout << brute_force(vec) << endl;
}
//////////////////////
vector<int> new_vec = {5, 6, 7, 8};
if(optimized_search(new_vec) == -1) {
cout << "None";
}
else {
cout << optimized_search(new_vec) << endl;
}
return 0;
}