Skip to content

Instantly share code, notes, and snippets.

@adamkorg
adamkorg / leetcode_278.cpp
Created April 30, 2020 16:02
Leetcode 278: First Bad Version
#include <iostream>
using namespace std;
//leetcode supplied function (I've created an example):
bool isBadVersion(int n) {
return (n >= 4);
}
int firstBadVersion(int n) {
@adamkorg
adamkorg / leetcode_277b.cpp
Created April 21, 2020 22:12
Leetcode 277: Find the Celebrity (O(n))
#include <iostream>
using namespace std;
bool knows(int a, int b);
int findCelebrity(int n) {
if (n==0) return -1;
int celeb = 0;
for (int i=1; i<n; ++i) {
@adamkorg
adamkorg / leetcode_277a.cpp
Created April 21, 2020 22:11
Leetcode 277: Find the Celebrity (O(n^2))
#include <iostream>
using namespace std;
bool knows(int a, int b);
int findCelebrity(int n) {
for (int b=0; b<n; ++b) {
int count=0;
for (int a=0; a<n; ++n) {
@adamkorg
adamkorg / leetcode_276c.cpp
Created April 11, 2020 12:53
Leetcode 276: Paint Fence (O(1) space)
#include <iostream>
#include <vector>
using namespace std;
int numWays(int n, int k) {
if (n==0 || k==0) return 0;
if (n==1) return k;
if (n==2) return k*k;
vector<int> dp {0,1,k};
@adamkorg
adamkorg / leetcode_276b.cpp
Created April 11, 2020 12:52
Leetcode 276: Paint Fence (O(n) space)
#include <iostream>
#include <vector>
using namespace std;
int numWays(int n, int k) {
if (n==0 || k==0) return 0;
vector<int> dp(n,1);
for (int c=1; c<n; ++c) {
@adamkorg
adamkorg / leetcode_276a.cpp
Created April 11, 2020 12:51
Leetcode 276: Paint Fence (O(n^2) space)
#include <iostream>
#include <vector>
using namespace std;
int numWays(int n, int k) {
if (n==0 || k==0) return 0;
vector<vector<int>> dp(k, vector<int>(n,1));
for (int c=1; c<n; ++c) {
@adamkorg
adamkorg / leetcode_275b.cpp
Created April 11, 2020 12:23
Leetcode 275: H-Index II (binary search)
#include <iostream>
#include <vector>
using namespace std;
int hIndex(vector<int>& citations) {
int h=0, len=citations.size();
int l=0, r=len-1, m=l+(r-l)/2;
while (l <= r) {
m = l+(r-l)/2;
@adamkorg
adamkorg / leetcode_275a.cpp
Created April 11, 2020 12:21
Leetcode 275: H-Index II (linear)
#include <iostream>
#include <vector>
using namespace std;
int hIndex(vector<int>& citations) {
int h=0, len=citations.size();
for (int i=len-1; i>=0; --i) {
if (citations[i] >= len-i) h++;
else break;
@adamkorg
adamkorg / leetcode_274.cpp
Created April 7, 2020 10:02
Leetcode 274: H-Index
#include <iostream>
#include <vector>
using namespace std;
int hIndex(vector<int>& citations) {
sort(citations.begin(), citations.end(), greater<int>());
int h = 0;
for (int i=0; i<citations.size(); ++i) {
if (citations[i] > i) h=i+1;
@adamkorg
adamkorg / leetcode_273.cpp
Created April 5, 2020 11:55
Leetcode 273: Integer to English Words
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string concat(string str, const string& strAdd) {
if (!strAdd.empty() && strAdd != "Zero") {
str += " ";
str += strAdd;