Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitbd1720c

Browse files
authored
Added tasks 136-155
1 parentc5d8adb commitbd1720c

File tree

21 files changed

+990
-0
lines changed

21 files changed

+990
-0
lines changed

‎README.md‎

Lines changed: 35 additions & 0 deletions
Large diffs are not rendered by default.
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// #Easy #Top_100_Liked_Questions #Top_Interview_Questions #Array #Bit_Manipulation
2+
// #Data_Structure_II_Day_1_Array #Algorithm_I_Day_14_Bit_Manipulation #Udemy_Integers
3+
// #Big_O_Time_O(N)_Space_O(1) #2024_05_27_Time_11_ms_(82.25%)_Space_19.1_MB_(84.99%)
4+
5+
#include<vector>
6+
usingnamespacestd;
7+
8+
classSolution {
9+
public:
10+
intsingleNumber(vector<int>& nums) {
11+
int res =0;
12+
for (int num : nums) {
13+
res ^= num;
14+
}
15+
return res;
16+
}
17+
};
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
136\. Single Number
2+
3+
Easy
4+
5+
Given a**non-empty** array of integers`nums`, every element appears_twice_ except for one. Find that single one.
6+
7+
You must implement a solution with a linear runtime complexity and use only constant extra space.
8+
9+
**Example 1:**
10+
11+
**Input:** nums =[2,2,1]
12+
13+
**Output:** 1
14+
15+
**Example 2:**
16+
17+
**Input:** nums =[4,1,2,1,2]
18+
19+
**Output:** 4
20+
21+
**Example 3:**
22+
23+
**Input:** nums =[1]
24+
25+
**Output:** 1
26+
27+
**Constraints:**
28+
29+
* <code>1 <= nums.length <= 3 * 10<sup>4</sup></code>
30+
* <code>-3 * 10<sup>4</sup> <= nums[i] <= 3 * 10<sup>4</sup></code>
31+
* Each element in the array appears twice except for one element which appears only once.
32+
33+
To solve the "Single Number" problem in Java with a`Solution` class, we'll use bitwise XOR operation. Below are the steps:
34+
35+
1.**Create a`Solution` class**: Define a class named`Solution` to encapsulate our solution methods.
36+
37+
2.**Create a`singleNumber` method**: This method takes an array`nums` as input and returns the single number that appears only once.
38+
39+
3.**Initialize a variable to store the result**: Initialize a variable`singleNumber` to 0.
40+
41+
4.**Iterate through the array and perform bitwise XOR operation**: Iterate through the array`nums`. For each number`num` in the array, perform bitwise XOR operation with the`singleNumber`.
42+
43+
5.**Return the result**: After iterating through the entire array, the`singleNumber` variable will store the single number that appears only once. Return`singleNumber`.
44+
45+
Here's the Java implementation:
46+
47+
```java
48+
classSolution {
49+
publicintsingleNumber(int[]nums) {
50+
int singleNumber=0;// Initialize variable to store result
51+
52+
// Perform bitwise XOR operation on all elements in the array
53+
for (int num: nums) {
54+
singleNumber^= num;
55+
}
56+
57+
return singleNumber;// Return the single number
58+
}
59+
}
60+
```
61+
62+
This implementation follows the steps outlined above and efficiently finds the single number that appears only once in the given array using bitwise XOR operation in Java.
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Hash_Table #Linked_List
2+
// #Programming_Skills_II_Day_14 #Udemy_Linked_List #Big_O_Time_O(N)_Space_O(N)
3+
// #2024_05_27_Time_5_ms_(65.69%)_Space_12.9_MB_(73.88%)
4+
5+
/*
6+
// Definition for a Node.
7+
class Node {
8+
public:
9+
int val;
10+
Node* next;
11+
Node* random;
12+
13+
Node(int _val) {
14+
val = _val;
15+
next = NULL;
16+
random = NULL;
17+
}
18+
};
19+
*/
20+
classSolution {
21+
public:
22+
Node*copyRandomList(Node* head) {
23+
if (head ==nullptr) {
24+
returnnullptr;
25+
}
26+
Node* curr = head;
27+
// First pass to create cloned nodes and insert them between original nodes
28+
while (curr !=nullptr) {
29+
Node* clonedNode =newNode(curr->val, curr->next,nullptr);
30+
curr->next = clonedNode;
31+
curr = clonedNode->next;
32+
}
33+
// Second pass to update random pointers of cloned nodes
34+
curr = head;
35+
while (curr !=nullptr) {
36+
if (curr->random !=nullptr) {
37+
curr->next->random = curr->random->next;
38+
}
39+
curr = curr->next->next;
40+
}
41+
// Third pass to separate original and cloned nodes
42+
curr = head;
43+
Node* newHead = curr->next;
44+
while (curr !=nullptr) {
45+
Node* clonedNode = curr->next;
46+
curr->next = clonedNode->next;
47+
if (clonedNode->next !=nullptr) {
48+
clonedNode->next = clonedNode->next->next;
49+
}
50+
curr = curr->next;
51+
}
52+
return newHead;
53+
}
54+
};
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
138\. Copy List with Random Pointer
2+
3+
Medium
4+
5+
A linked list of length`n` is given such that each node contains an additional random pointer, which could point to any node in the list, or`null`.
6+
7+
Construct a[**deep copy**](https://en.wikipedia.org/wiki/Object_copying#Deep_copy) of the list. The deep copy should consist of exactly`n`**brand new** nodes, where each new node has its value set to the value of its corresponding original node. Both the`next` and`random` pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state.**None of the pointers in the new list should point to nodes in the original list**.
8+
9+
For example, if there are two nodes`X` and`Y` in the original list, where`X.random --> Y`, then for the corresponding two nodes`x` and`y` in the copied list,`x.random --> y`.
10+
11+
Return_the head of the copied linked list_.
12+
13+
The linked list is represented in the input/output as a list of`n` nodes. Each node is represented as a pair of`[val, random_index]` where:
14+
15+
*`val`: an integer representing`Node.val`
16+
*`random_index`: the index of the node (range from`0` to`n-1`) that the`random` pointer points to, or`null` if it does not point to any node.
17+
18+
Your code will**only** be given the`head` of the original linked list.
19+
20+
**Example 1:**
21+
22+
![](https://assets.leetcode.com/uploads/2019/12/18/e1.png)
23+
24+
**Input:** head =[[7,null],[13,0],[11,4],[10,2],[1,0]]
25+
26+
**Output:**[[7,null],[13,0],[11,4],[10,2],[1,0]]
27+
28+
**Example 2:**
29+
30+
![](https://assets.leetcode.com/uploads/2019/12/18/e2.png)
31+
32+
**Input:** head =[[1,1],[2,1]]
33+
34+
**Output:**[[1,1],[2,1]]
35+
36+
**Example 3:**
37+
38+
**![](https://assets.leetcode.com/uploads/2019/12/18/e3.png)**
39+
40+
**Input:** head =[[3,null],[3,0],[3,null]]
41+
42+
**Output:**[[3,null],[3,0],[3,null]]
43+
44+
**Example 4:**
45+
46+
**Input:** head =[]
47+
48+
**Output:**[]
49+
50+
**Explanation:** The given linked list is empty (null pointer), so return null.
51+
52+
**Constraints:**
53+
54+
*`0 <= n <= 1000`
55+
*`-10000 <= Node.val <= 10000`
56+
*`Node.random` is`null` or is pointing to some node in the linked list.
57+
58+
To solve the "Copy List with Random Pointer" problem in Java with a`Solution` class, we'll use a HashMap to maintain a mapping between the original nodes and their corresponding copied nodes. Below are the steps:
59+
60+
1.**Create a`Solution` class**: Define a class named`Solution` to encapsulate our solution methods.
61+
62+
2.**Create a`copyRandomList` method**: This method takes the head node of the original linked list as input and returns the head node of the copied linked list.
63+
64+
3.**Initialize a HashMap**: Create a HashMap named`nodeMap` to store the mapping between original nodes and their corresponding copied nodes.
65+
66+
4.**Create a deep copy of the list**: Iterate through the original linked list and create a deep copy of each node. For each node`originalNode` in the original linked list:
67+
- Create a new node`copyNode` with the same value as`originalNode`.
68+
- Put the mapping between`originalNode` and`copyNode` in the`nodeMap`.
69+
- Set the`copyNode`'s`next` and`random` pointers accordingly.
70+
- Attach the`copyNode` to the copied linked list.
71+
72+
5.**Return the head of the copied linked list**: After creating the deep copy of the entire list, return the head node of the copied linked list.
73+
74+
Here's the Java implementation:
75+
76+
```java
77+
importjava.util.HashMap;
78+
importjava.util.Map;
79+
80+
classSolution {
81+
publicNodecopyRandomList(Nodehead) {
82+
if (head==null)returnnull;// Check for empty list
83+
84+
Map<Node,Node> nodeMap=newHashMap<>();// Initialize HashMap to store mapping between original and copied nodes
85+
86+
// Create a deep copy of each node in the list
87+
Node current= head;
88+
while (current!=null) {
89+
Node copyNode=newNode(current.val);// Create a new copy node
90+
nodeMap.put(current, copyNode);// Put mapping between original and copied nodes in the map
91+
current= current.next;// Move to the next node
92+
}
93+
94+
// Set the next and random pointers of copied nodes
95+
current= head;
96+
while (current!=null) {
97+
Node copyNode= nodeMap.get(current);// Get copied node
98+
copyNode.next= nodeMap.getOrDefault(current.next,null);// Set next pointer
99+
copyNode.random= nodeMap.getOrDefault(current.random,null);// Set random pointer
100+
current= current.next;// Move to the next node
101+
}
102+
103+
return nodeMap.get(head);// Return the head of the copied linked list
104+
}
105+
106+
// Definition for a Node
107+
classNode {
108+
int val;
109+
Node next, random;
110+
111+
Node(intval) {
112+
this.val= val;
113+
this.next=null;
114+
this.random=null;
115+
}
116+
}
117+
}
118+
```
119+
120+
This implementation follows the steps outlined above and efficiently constructs a deep copy of the linked list with random pointers in Java.
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #String #Hash_Table
2+
// #Dynamic_Programming #Trie #Memoization #Algorithm_II_Day_15_Dynamic_Programming
3+
// #Dynamic_Programming_I_Day_9 #Udemy_Dynamic_Programming #Big_O_Time_O(M+max*N)_Space_O(M+N+max)
4+
// #2024_05_27_Time_5_ms_(70.91%)_Space_10.8_MB_(74.12%)
5+
6+
#include<string>
7+
#include<vector>
8+
#include<unordered_set>
9+
usingnamespacestd;
10+
11+
classSolution {
12+
public:
13+
boolwordBreak(string s, vector<string>& wordDict) {
14+
unordered_set<string> set;
15+
int maxLen =0;
16+
vector<bool>flag(s.length() +1,false);
17+
18+
for (const string& word : wordDict) {
19+
set.insert(word);
20+
maxLen =max(maxLen, (int)word.length());
21+
}
22+
23+
for (int i =1; i <= maxLen; ++i) {
24+
if (dfs(s,0, i, maxLen, set, flag)) {
25+
returntrue;
26+
}
27+
}
28+
returnfalse;
29+
}
30+
31+
private:
32+
booldfs(const string& s,int start,int end,int maxLen, unordered_set<string>& set, vector<bool>& flag) {
33+
if (!flag[end] && set.count(s.substr(start, end - start))) {
34+
flag[end] =true;
35+
if (end == s.length()) {
36+
returntrue;
37+
}
38+
for (int i =1; i <= maxLen; ++i) {
39+
if (end + i <= s.length() &&dfs(s, end, end + i, maxLen, set, flag)) {
40+
returntrue;
41+
}
42+
}
43+
}
44+
returnfalse;
45+
}
46+
};
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
139\. Word Break
2+
3+
Medium
4+
5+
Given a string`s` and a dictionary of strings`wordDict`, return`true` if`s` can be segmented into a space-separated sequence of one or more dictionary words.
6+
7+
**Note** that the same word in the dictionary may be reused multiple times in the segmentation.
8+
9+
**Example 1:**
10+
11+
**Input:** s = "leetcode", wordDict =["leet","code"]
12+
13+
**Output:** true
14+
15+
**Explanation:** Return true because "leetcode" can be segmented as "leet code".
16+
17+
**Example 2:**
18+
19+
**Input:** s = "applepenapple", wordDict =["apple","pen"]
20+
21+
**Output:** true
22+
23+
**Explanation:** Return true because "applepenapple" can be segmented as "apple pen apple". Note that you are allowed to reuse a dictionary word.
24+
25+
**Example 3:**
26+
27+
**Input:** s = "catsandog", wordDict =["cats","dog","sand","and","cat"]
28+
29+
**Output:** false
30+
31+
**Constraints:**
32+
33+
*`1 <= s.length <= 300`
34+
*`1 <= wordDict.length <= 1000`
35+
*`1 <= wordDict[i].length <= 20`
36+
*`s` and`wordDict[i]` consist of only lowercase English letters.
37+
* All the strings of`wordDict` are**unique**.
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// #Easy #Top_100_Liked_Questions #Top_Interview_Questions #Hash_Table #Two_Pointers #Linked_List
2+
// #Data_Structure_I_Day_7_Linked_List #Udemy_Linked_List #Big_O_Time_O(N)_Space_O(1)
3+
// #2024_05_27_Time_7_ms_(84.60%)_Space_10.7_MB_(18.04%)
4+
5+
/**
6+
* Definition for singly-linked list.
7+
* struct ListNode {
8+
* int val;
9+
* ListNode *next;
10+
* ListNode(int x) : val(x), next(NULL) {}
11+
* };
12+
*/
13+
classSolution {
14+
public:
15+
boolhasCycle(ListNode* head) {
16+
if (head ==nullptr) {
17+
returnfalse;
18+
}
19+
ListNode* fast = head->next;
20+
ListNode* slow = head;
21+
while (fast !=nullptr && fast->next !=nullptr) {
22+
if (fast == slow) {
23+
returntrue;
24+
}
25+
fast = fast->next->next;
26+
slow = slow->next;
27+
}
28+
returnfalse;
29+
}
30+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp