#237 Delete Node in a Linked List
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4
and you are given the third node with value 3
, the linked list should become 1 -> 2 -> 4
after calling your function.
The best code so far:
这个题太简单,好像没有啥好优化的?
所以这里判断是否是最后一个节点,是应该 node == NULL 还是还是 node->next == NULL 呢?
Code by S:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 void deleteNode(ListNode* node) { 12 if (node->next == NULL) 13 return; 14 node->val = node->next->val; 15 node->next = node->next->next; 16 17 } 18 };
开始用.代替了->报错了几次,其实应该可以的。
【讨论】:是否需要删掉那个不要的节点呢?(new一个node,再delete掉?)
#238 Product of Array Except Self
Given an array of n integers where n > 1, nums
, return an array output
such that output[i]
is equal to the product of all the elements of nums
except nums[i]
.
Solve it without division and in O(n).
For example, given [1,2,3,4]
, return [24,12,8,6]
.
The best code so far:
1 class Solution { 2 public: 3 vector<int> productExceptSelf(vector<int>& nums) 4 { 5 int len = nums.size(); 6 vector<int> result(len , 0); 7 result[0] = 1; 8 for(int i = 1 ; i < len ; i++) 9 { 10 result[i] = result[i-1] * nums[i-1]; //result存储的是0~i-1总共i个数字的乘积 11 } 12 int postPro = 1; 13 for(int j = len-1 ; j >= 0 ; j--) 14 { 15 result[j] *= postPro; 16 postPro *= nums[j]; //postPro表示从j到len-1个数字的乘积 17 } 18 return result; 19 } 20 };
http://blog.csdn.net/u012243115/article/details/46906417
少了一个数组和一遍扫描。
Code by S:
1 class Solution { 2 public: 3 vector<int> productExceptSelf(vector<int>& nums) { 4 int l = nums.size(); 5 vector<int> left; 6 vector<int> right; 7 vector<int> output; 8 int flag = 1; 9 for(int i = 0; i < l-1; i++){ 10 flag *= nums[i]; 11 left.push_back(flag); 12 } 13 flag = 1; 14 for(int j = l-1; j > 0; j--){ 15 flag *= nums[j]; 16 right.push_back(flag); 17 } 18 output.push_back(right[l-2]); 19 for(int i = 1 ; i < l-1; i++){ 20 output.push_back(left[i-1]*right[l-2-i]); 21 } 22 output.push_back(left[l-2]); 23 return output; 24 25 } 26 };
开了三个数组,而且大小还比实际的小一位,感觉有点不舒服,写到第三个循环才意识到这个问题。
想到算法就不难了,但是并没想到。自己想的时候还想到矩阵神马的。