/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/classSolution{public:
ListNode* h;/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */Solution(ListNode* head){
h = head;}/** Returns a random node's value. */intgetRandom(){int c =-1, n =0;for(auto p = h; p; p = p->next){
n ++;if(rand()% n ==0) c = p->val;}return c;}};/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(head);
* int param_1 = obj->getRandom();
*/
import java.util.Random;
Class Solution{publicstaticvoidmain(String[] args){int[] nums =newint[]{1,2,3,4,5};
Solution s =newSolution();int[] ans = s.sample(nums,3);for(int i =0; i < ans.length; i++){
System.out.printf("%d ", ans[i]);}}privateint[]sample(int[] nums,int n){
Random rd =newRandom();int[] ans =newint[n];for(int i =0; i < nums.length; i++){if(i < n){
ans[i]= nums[i];}else{if(rd.nextInt(i+1)< n){
ans[rd.nextInt(n)]= nums[i];}}}return ans;}}
# Definition for singly-linked list.# class ListNode:# def __init__(self, val=0, next=None):# self.val = val# self.next = nextclassSolution:def__init__(self, head: ListNode):"""
@param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node.
"""
self.head = head
defgetRandom(self)->int:"""
Returns a random node's value.
"""
time =0
p = self.head
res =Nonewhile p:
time +=1if random.randint(1,time)==1:
res = p.val
p = p.nextreturn res
# Your Solution object will be instantiated and called as such:# obj = Solution(head)# param_1 = obj.getRandom()
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/type Solution struct{
head *ListNode
r *rand.Rand
}/** @param head The linked list's head.
Note that the head is guaranteed to be not null, so it contains at least one node. */funcConstructor(head *ListNode) Solution {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
solution := Solution{
head: head,
r: r,}return solution
}/** Returns a random node's value. */func(this *Solution)GetRandom()int{
i :=2
cur := this.head.Next
val := this.head.Val
for cur !=nil{if this.r.Intn(i)+1== i {
val = cur.Val
}
i++
cur = cur.Next
}return val
}
### 复杂度分析
时间复杂度:O(n)至少要遍历到n个元素
空间复杂度:O(1)常数空间复杂度
/**
* Your Solution object will be instantiated and called as such:
* obj := Constructor(head);
* param_1 := obj.GetRandom();
*/
第三百八十三题
classSolution{public:boolcanConstruct(string a, string b){
unordered_map<char,int> hash;for(auto c: b) hash[c]++;for(auto c: a)if(!hash[c])returnfalse;else hash[c]--;returntrue;}};
classSolution{publicbooleancanConstruct(String ransomNote, String magazine){char[] chars1 = ransomNote.toCharArray();char[] chars2 = magazine.toCharArray();if(chars1.length > chars2.length){returnfalse;}int[] rans =newint[26];int[] maga =newint[26];for(char c : chars1){
rans[c -'a']++;}for(char c : chars2){
maga[c -'a']++;}for(int i =0; i < rans.length ; i++){if(rans[i]> maga[i]){returnfalse;}}returntrue;}}
classSolution:defcanConstruct(self, ransomNote:str, magazine:str)->bool:
hash_table_m = collections.Counter(magazine)
hash_table_r = collections.Counter(ransomNote)"""for i in hash_table_r:
if hash_table_r[i] > hash_table_m[i]:
return False
return True"""returnnot hash_table_r - hash_table_m
classSolution{public:
vector<int> a;Solution(vector<int>& nums){
a = nums;}/** Resets the array to its original configuration and return it. */
vector<int>reset(){return a;}/** Returns a random shuffling of the array. */
vector<int>shuffle(){auto b = a;int n = a.size();for(int i =0; i < n; i ++)swap(b[i], b[i +rand()%(n - i)]);return b;}};/**
* Your Solution object will be instantiated and called as such:
* Solution* obj = new Solution(nums);
* vector<int> param_1 = obj->reset();
* vector<int> param_2 = obj->shuffle();
*/
classSolution{privateint[] array;privateint[] original;
Random rand =newRandom();privateintrandRange(int min,int max){return rand.nextInt(max - min)+ min;}privatevoidswapAt(int i,int j){int temp = array[i];
array[i]= array[j];
array[j]= temp;}publicSolution(int[] nums){
array = nums;
original = nums.clone();}publicint[]reset(){
array = original;
original = original.clone();return original;}publicint[]shuffle(){for(int i =0; i < array.length; i++){swapAt(i,randRange(i, array.length));}return array;}}
type Solution struct{
arr []int}funcConstructor(nums []int) Solution {return Solution{nums}}/** Resets the array to its original configuration and return it. */func(this *Solution)Reset()[]int{return this.arr
}/** Returns a random shuffling of the array. */func(this *Solution)Shuffle()[]int{
n :=len(this.arr)
res :=make([]int, n)copy(res, this.arr)for i := n-1; i >=0; i--{
rand := rand.Intn(i+1)// math.rand中的Intn(i+1)返回[0, i]范围的整数,每次数组在下标index为[0, i]范围内随机找一个下标对应的元素与当前位置i处的元素进行交换
res[i], res[rand]= res[rand], res[i]// 对应位置元素交换,也可以使用如下代码// tmp := res[i]// res[i] = res[rand]// res[rand] = tmp}return res
}/**
* Your Solution object will be instantiated and called as such:
* obj := Constructor(nums);
* param_1 := obj.Reset();
* param_2 := obj.Shuffle();
*/
第三百八十五题
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* class NestedInteger {
* public:
* // Constructor initializes an empty nested list.
* NestedInteger();
*
* // Constructor initializes a single integer.
* NestedInteger(int value);
*
* // Return true if this NestedInteger holds a single integer, rather than a nested list.
* bool isInteger() const;
*
* // Return the single integer that this NestedInteger holds, if it holds a single integer
* // The result is undefined if this NestedInteger holds a nested list
* int getInteger() const;
*
* // Set this NestedInteger to hold a single integer.
* void setInteger(int value);
*
* // Set this NestedInteger to hold a nested list and adds a nested integer to it.
* void add(const NestedInteger &ni);
*
* // Return the nested list that this NestedInteger holds, if it holds a nested list
* // The result is undefined if this NestedInteger holds a single integer
* const vector<NestedInteger> &getList() const;
* };
*/classSolution{public:
NestedInteger deserialize(string s){int u =0;returndfs(s, u);}
NestedInteger dfs(string& s,int& u){
NestedInteger res;if(s[u]=='['){
u ++;// 跳过左括号while(s[u]!=']') res.add(dfs(s, u));
u ++;// 跳过右括号if(u < s.size()&& s[u]==',') u ++;// 跳过逗号}else{int k = u;while(k < s.size()&& s[k]!=','&& s[k]!=']') k ++;
res.setInteger(stoi(s.substr(u, k - u)));if(k < s.size()&& s[k]==',') k ++;// 跳过逗号
u = k;}return res;}};
classSolution{//递归函数通过字符数组和cur下标确定要处理的位置char[] chars;int cur =0;public NestedInteger deserialize(String s){
chars = s.toCharArray();//本身不是一个集合而是一个整数的情况if(chars[0]!='[')returnnewNestedInteger(Integer.valueOf(s));//调用递归函数返回根集合returngetNest();}public NestedInteger getNest(){
NestedInteger nest =newNestedInteger();int num =0;//num用于缓存用逗号分割的整数类型的值int sign =1;//当前记录的整数的符号,1代表整数,-1代表负数while(cur!=chars.length-1){
cur ++;if(chars[cur]==',')continue;if(chars[cur]=='[') nest.add(getNest());//遇到[递归获取子集合elseif(chars[cur]==']')return nest;elseif(chars[cur]=='-') sign =-1;else{//是数字的情况
num =10*num + sign *(chars[cur]-'0');//如果下一个字符是,或者]说明当前数字已经记录完了,需要加入集合中if(chars[cur+1]==','||chars[cur+1]==']'){
nest.add(newNestedInteger(num));
num =0;
sign =1;}}}return null;}}
classSolution:defdeserialize(self, s:str)-> NestedInteger:defdfs(elem):iftype(elem)==int:return NestedInteger(elem)
li = NestedInteger()# 这个对象为空时是一个空列表for i in elem:
li.add(dfs(i))return li
return dfs(eval(s))# empty123 = NestedInteger() #空列表# num123=NestedInteger(123)# empty123.add(num123)# empty456=NestedInteger()#空列表# num456=NestedInteger(456)# empty456.add(num456)# empty123.add(empty456)# return empty123
classSolution{public:
vector<int> res;
vector<int>lexicalOrder(int n){for(int i =1; i <=9; i ++)dfs(i, n);return res;}voiddfs(int cur,int n){if(cur <= n) res.push_back(cur);elsereturn;for(int i =0; i <=9; i ++)dfs(cur *10+ i, n);}};
classSolution{// public List<Integer> lexicalOrder(int n) {// List<Integer> list = new ArrayList<>();// int curr = 1;// //10叉树的先序遍历// for(int i=0;i<n;i++){// list.add(curr);// if(curr*10<=n){// curr*=10;//进入下一层// }else{// if(curr>=n) curr/=10;//如果这一层结束了// curr+=1;// while(curr%10==0) curr/=10;//如果>10就要返回上一层// }// }// return list;// }public List<Integer>lexicalOrder(int n){
List<Integer> list =newArrayList<>();for(int i =1; i <10; i++){dfs(n, i, list);}return list;}privatevoiddfs(int n,int i,List<Integer>list){if(i>n){return;}
list.add(i);for(int j=0;j<=9;j++){dfs(n,i*10+j,list);}}}
classSolution:deflexicalOrder(self, n:int)-> List[int]:# N叉树 深度优先搜索
res=[]defdfs(i):
cur = i
if cur >n:return
res.append(cur)for j inrange(10):
dfs(cur*10+j)for i inrange(1,10):
dfs(i)return res
funclexicalOrder(n int)[]int{
ret :=make([]int,0)
num :=1for{if num <= n {
ret =append(ret, num)
num *=10}else{
num /=10for num %10==9{
num /=10}if num ==0{break}
num++}}return ret
}
第三百八十七题
classSolution{public:intfirstUniqChar(string s){
unordered_map<char,int> hash;for(auto c: s) hash[c]++;for(int i =0; i < s.size(); i ++)if(hash[s[i]]==1)return i;return-1;}};
classSolution{publicintfirstUniqChar(String s){
Map<Character, Integer> position =newHashMap<Character, Integer>();int n = s.length();for(int i =0; i < n;++i){char ch = s.charAt(i);if(position.containsKey(ch)){
position.put(ch,-1);}else{
position.put(ch, i);}}int first = n;for(Map.Entry<Character, Integer> entry : position.entrySet()){int pos = entry.getValue();if(pos !=-1&& pos < first){
first = pos;}}if(first == n){
first =-1;}return first;}}
classSolution:deffirstUniqChar(self, s:str)->int:
position =dict()
n =len(s)for i, ch inenumerate(s):if ch in position:
position[ch]=-1else:
position[ch]= i
first = n
for pos in position.values():if pos !=-1and pos < first:
first = pos
if first == n:
first =-1return first
funcfirstUniqChar(s string)int{
n :=len(s)
pos :=[26]int{}for i :=range pos[:]{
pos[i]= n
}for i, ch :=range s {
ch -='a'if pos[ch]== n {
pos[ch]= i
}else{
pos[ch]= n +1}}
ans := n
for_, p :=range pos[:]{if p < ans {
ans = p
}}if ans < n {return ans
}return-1}
第三百八十八题
classSolution{public:intlengthLongestPath(string input){
stack<int> stk;int res =0;for(int i =0, sum =0; i < input.size(); i ++){int k =0;while(i < input.size()&& input[i]=='\t') i ++, k ++;while(stk.size()> k) sum -= stk.top(), stk.pop();int j = i;while(j < input.size()&& input[j]!='\n') j ++;int len = j - i;
stk.push(len), sum += len;if(input.substr(i, len).find('.')!=-1)
res =max(res, sum +(int)stk.size()-1);
i = j;}return res;}};
classSolution{publicintlengthLongestPath(String input){
Stack<Integer> stack =newStack<>();
stack.push(0);int ans =0;// 以 \n 分割成字符串数组
String[] str = input.split("\n");// dir,\tsubdir1,\tsubdir2,\tfile.extfor(String s : str){// level 代表当前字符串的首字母索引// 字符串前面可能会有多个 \t,故使用 lastIndexOf 找出最后一个 \t 位置即可int level = s.lastIndexOf("\t")+1;while(level +1< stack.size()){
stack.pop();}// 之前入栈的字符串 + 当前遍历到的字符串的长度int len = stack.peek()+(s.length()- level +1);
stack.push(len);if(s.contains(".")){
ans = Math.max(ans, len -1);}}return ans;}}
classSolution:deflengthLongestPath(self,input:str)->int:
prefixSum =[0]
res =0for s ininput.split('\n'):
level =0# 当前层级while s[level]=='\t':
level +=1
sLen =len(s)- level
# 如果是文件,比较最大值。if'.'in s:
res =max(res, prefixSum[level]+ sLen)continue# 如果是文件夹,将当前层级的字符串数目(包含末尾斜杆)保存。if level +1<len(prefixSum):
prefixSum[level +1]= prefixSum[level]+ sLen +1else:
prefixSum.append(prefixSum[-1]+ sLen +1)return res
funclengthLongestPath(input string)int{
s := strings.Split(input,"\n")var paths []Path // 所有路径,包括缩进层次和路径for_, v :=range s {
level := strings.Count(v,"\t")
paths =append(paths, Path{v[level:], level})}var stack []Path
var result intfor_, v :=range paths {// 总是保证栈顶是小于该文件的缩进的forlen(stack)!=0&& stack[len(stack)-1].Level >= v.Level {
stack = stack[:len(stack)-1]}
stack =append(stack, v)if strings.Contains(v.Content,"."){
result =max(result,calLen(stack))}}return result
}type Path struct{
Content string
Level int}funccalLen(stack []Path)int{
result :=0for_, v :=range stack {
result +=len(v.Content)}// 多加 len(stack) - 1 个 "/"return result +len(stack)-1}funcmax(num1, num2 int)int{if num1 > num2 {return num1
}return num2
}