Skip to content

Create 0706-design-hashmap.cpp #2313

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

// If target is not found in the array, return [-1, -1].

// TC : O(log n) , SC : O(1)



class Solution {

public:
int f(vector<int>&arr,int start,int end,int x,int res){

while(start<=end){
int mid = start + (end-start)/2;

if(arr[mid]==x){
res = mid;
end = mid-1;
}
else if(arr[mid]<x) start = mid+1;
else end = mid-1;

}
return res;

}


public:
int l(vector<int>&arr,int start,int end,int x,int res){

while(start<=end){
int mid = start + (end-start)/2;

if(arr[mid]==x){
res = mid;
start = mid+1;
}
else if(arr[mid]<x) start = mid+1;
else end = mid-1;

}
return res;

}


public:
vector<int> searchRange(vector<int>& nums, int target) {

int start = 0;
int end = nums.size()-1;
int res = -1;

vector<int>v;
int first = f(nums,start,end,target,res);
int last = l(nums,start,end,target,res);

v.push_back(first);
v.push_back(last);

return v;


}
};
32 changes: 32 additions & 0 deletions cpp/0706-design-hashmap.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Design a HashMap without using any built-in hash table libraries.

// Implement the MyHashMap class:

// MyHashMap() initializes the object with an empty map.
// void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value.
// int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key.
// void remove(key) removes the key and its corresponding value if the map contains the mapping for the key.


class MyHashMap {
public:

unordered_map<int,int> mp;

MyHashMap() {

}

void put(int key, int value) {
mp[key] = value;
}

int get(int key) {
if(mp.find(key)!=mp.end()) return mp[key];
return -1;
}

void remove(int key) {
mp.erase(key);
}
};