From 22d8949c0e24d17c3d35526a322b48006210ec40 Mon Sep 17 00:00:00 2001 From: Your Name Date: Mon, 4 Oct 2021 14:46:15 +0530 Subject: [PATCH] Added C++ folder and some basic programs --- ...rst and last occurence in sorted array.cpp | 54 +++++++++++++++++++ C++/Kadane's algo(Maximum Subarray).cpp | 14 +++++ C++/Reverse LinkedList.cpp | 25 +++++++++ 3 files changed, 93 insertions(+) create mode 100644 C++/First and last occurence in sorted array.cpp create mode 100644 C++/Kadane's algo(Maximum Subarray).cpp create mode 100644 C++/Reverse LinkedList.cpp diff --git a/C++/First and last occurence in sorted array.cpp b/C++/First and last occurence in sorted array.cpp new file mode 100644 index 0000000..9bcdea6 --- /dev/null +++ b/C++/First and last occurence in sorted array.cpp @@ -0,0 +1,54 @@ +class Solution { +public: + int firstoccurence(vector& nums,int target){ + int s = 0; + int e = nums.size()-1; + int ans = -1; + while(s<=e){ + int mid = s + (e-s)/2; + if(nums[mid] == target){ + ans = mid ; + e = mid - 1; + } + else if(target& nums,int target){ + int s = 0; + int e = nums.size()-1; + int ans = -1; + while(s<=e){ + int mid = s + (e-s)/2; + if(nums[mid] == target){ + ans = mid ; + s = mid + 1; + } + else if(target searchRange(vector& nums, int target) { + vector ans(2,-1); + int first = firstoccurence(nums,target); + if(first == -1) + return ans; + int last = lastoccurence(nums,target); + ans[0]=first; + ans[1]=last; + + return ans; + + + } +}; \ No newline at end of file diff --git a/C++/Kadane's algo(Maximum Subarray).cpp b/C++/Kadane's algo(Maximum Subarray).cpp new file mode 100644 index 0000000..511f84b --- /dev/null +++ b/C++/Kadane's algo(Maximum Subarray).cpp @@ -0,0 +1,14 @@ +class Solution { +public: + int maxSubArray(vector& nums) { + int mth = nums[0]; + int msf = nums[0]; + for(int i = 1 ; i < nums.size() ; i ++){ + mth+=nums[i]; + mth = max(mth,nums[i]); + msf = max(msf,mth); + } + return msf; + + } +}; \ No newline at end of file diff --git a/C++/Reverse LinkedList.cpp b/C++/Reverse LinkedList.cpp new file mode 100644 index 0000000..054773c --- /dev/null +++ b/C++/Reverse LinkedList.cpp @@ -0,0 +1,25 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode() : val(0), next(nullptr) {} + * ListNode(int x) : val(x), next(nullptr) {} + * ListNode(int x, ListNode *next) : val(x), next(next) {} + * }; + */ +class Solution { +public: + ListNode* reverseList(ListNode* head) { + ListNode * curr = head; + ListNode* prev = NULL; + + while(curr){ + ListNode *n = curr->next; + curr->next = prev; + prev = curr; + curr = n; + } + return prev; + } +}; \ No newline at end of file