classSolution { public: intfixedPoint(vector<int>& A){ for (int i = 0; i < A.size(); ++i) { if (A[i] == i) { return i; } } return-1; } };
由于数组A是升序的,所以还可以用 二分搜索 的算法,实现O(log N).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: intfixedPoint(vector<int>& A){ int lo = 0, hi = A.size(); while (lo < hi) { int mid = lo + (hi - lo) / 2; if (A[mid] < mid) { lo = mid + 1; } else { hi = mid; } } return A[lo] == lo ? lo : -1; } };
intcountDigitOne(int n) { int countr = 0; for (longlong i = 1; i <= n; i *= 10) { longlong divider = i * 10; countr += (n / divider) * i + min(max(n % divider - i + 1, 0LL), i); } return countr; }
根据以上解法,很容易扩充到任何数字。
需要注意数字0因为不能开头,所以需要特殊处理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution { // include n inthelper(int d, int n){ int ret = 0; for (longlong i = 1; i <= n; i *= 10) { longlong divisor = i * 10; ret += (n / divisor) * i + min(i, max(0LL, n % divisor - d * i + 1)) - (d == 0 ? i : 0); // cout << ret << " "; } // cout << n << " " << ret << endl; return ret; } public: intdigitsCount(int d, int low, int high){ returnhelper(d, high) - helper(d, low - 1); } };