83. Remove Duplicates from Sorted List
Easy
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2 Output: 1->2
Example 2:
Input: 1->1->2->3->3 Output: 1->2->3
BONUS:
很多时候,在对结构体进行相应的编码时,时而发现是用点运算符( . ),时而是用箭头运算符( -> );那么这两者之间的使用有什么区别么?
相同点:两者都是二元操作符,而且右边的操作数都是成员的名称。
不同点:点运算符( . )的左边操作数是一个结果为结构的表达式;
箭头运算符( -> )的左边的操作数是一个指向结构体的指针。
例如:
typedef struct // 定义一个结构体类型:DATA { char key[10]; // 结构体成员:key char name[20]; // 结构体成员:name int age; // 结构体成员:age }DATA; DATA data; // 声明一个结构体变量 DATA *pdata; // 声明一个指向结构体的指针 // 访问数据操作如下: data.age = 24; // 结构体变量通过点运算符( . )访问 pdata->age = 24; // 指向结构体的指针通过箭头运算符( -> )访问
Python version:
method 1:recursion seems the simplest method.
short:slow
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """
#or need two not before and behind if not head or not head.next: return head head.next=self.deleteDuplicates(head.next) return head if head.val !=head.next.val else head.next solu=Solution() node1=ListNode(1) node2=ListNode(2) node3=ListNode(2) node4=ListNode(4) node1.next=node2 node2.next=node3 node3.next=node4 head=node1 solu.deleteDuplicates(head) while head: print(head.val) head=head.next
88. Merge Sorted Array
Easy
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
- The number of elements initialized in nums1 and nums2 are m and n respectively.
- You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
Example:
Input: nums1 = [1,2,3,0,0,0], m = 3 nums2 = [2,5,6], n = 3 Output: [1,2,2,3,5,6]
ATTENTION:
1.when print nums1 directly put judge condition is <tail,I just thought tail is the
size of nums1,but tail-- had lost it size,so cannot directly use at this part
2.nums1 is the full-length one ,it's large enough to store all nums1&nums2,so this needn't
return is a void function.so use two index n+m-1.n-1 represent different part of nums1 to
make sum
#include<iostream> #include<string> #include<vector> using namespace std; class Solution { public: void merge(vector<int>& nums1,int m,vector<int>& nums2,int n) { int i=m-1; int j=n-1; int tail=n+m-1; while(j>=0) { nums1[tail--]=(i>=0&&nums1[i]>nums2[j])?nums1[i--]:nums2[j--]; } cout<<"END"<<endl; for(int i=0;i<n+m;i++) { cout<<nums1[i]<<endl; } } }; int main() { Solution s1; vector<int> nums1; nums1.push_back(1); nums1.push_back(2);nums1.push_back(3);nums1.push_back(0);nums1.push_back(0);nums1.push_back(0); cout<<"flag"<<endl; for(int i=0;i<nums1.size();i++) { cout<<nums1[i]<<endl; } vector<int> nums2;nums2.push_back(4);nums2.push_back(5);nums2.push_back(6); for(int i=0;i<nums2.size();i++) { cout<<nums2[i]<<endl; } int m=3,n=3; s1.merge(nums1,m,nums2,n); return 0; }
愿为天下目,萃聚六路华
浙公网安备 33010602011771号