121. 买卖股票的最佳时机
//暴力
class Solution {
public int maxProfit(int[] prices) {
int max = 0;
for(int i=0;i<prices.length;i++){
for(int j=i+1;j<prices.length;j++){
max = Math.max(max,prices[j]-prices[i]);
}
}
return max;
}
}
class Solution {
public int maxProfit(int[] prices) {
int min = Integer.MAX_VALUE;
int profit = 0;
for(int i=0;i<prices.length;i++){
min = Math.min(min,prices[i]);
profit = Math.max(profit,prices[i]-min);
}
return profit;
}
}
class Solution {
public int maxProfit(int[] prices) {
int length = prices.length;
if (length == 0) {
return 0;
}
int maxprice = 0, maxprofit = -1;
for (int i = length - 1; i >= 0; i --) {
if (prices[i] > maxprice) {
maxprice = prices[i];
}
int profit = maxprice - prices[i];
if (profit > maxprofit) {
maxprofit = profit;
}
}
return maxprofit;
}
}
1365. 有多少小于当前数字的数字
class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
int[] res = new int[nums.length];
for(int i = 0;i<nums.length;i++){
int count = 0;
for(int j = 0;j<nums.length;j++){
if(nums[i]>nums[j]){
count++;
}
}
res[i] = count;
}
return res;
}
}
class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) {
int n = nums.length;
int[] temp = new int[n];
temp = Arrays.copyOf(nums, n);
Arrays.sort(temp);
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < n; i++){
if(i == 0){
map.put(temp[i],0);
}else{
if(temp[i] > temp[i-1]){
map.put(temp[i],i);
}else{
map.put(temp[i],map.get(temp[i-1]));
}
}
}
for(int i = 0; i < n; i++){
temp[i] = map.get(nums[i]);
}
return temp;
}
}
class Solution {
public int[] smallerNumbersThanCurrent(int[] nums) { // 8, 1, 2, 2, 3
int len = nums.length;
Map<Integer, Set<Integer>> valueIndex = new HashMap<>(len); // 预存每个值与索引对应
for (int i = 0; i < len; i++) {
if (!valueIndex.containsKey(nums[i])) valueIndex.put(nums[i], new HashSet<>());
valueIndex.get(nums[i]).add(i);
}
int[] sortedArr = Arrays.copyOf(nums, len), res = new int[len];
Arrays.sort(sortedArr); // 1, 2, 2, 3, 8
for (int si = len - 1; si >= 0; si--) {
for (int i : valueIndex.get(sortedArr[si])) res[i] = si; // 同值的所有索引都更新
}
return res;
}
}
1290. 二进制链表转整数
//位运算
class Solution {
public int getDecimalValue(ListNode head) {
if (head == null)
return 0;
int ans = 0;
while (head != null) {
ans = (ans << 1) + head.val;
head = head.next;
}
return ans;
}
}
class Solution {
public int getDecimalValue(ListNode head) {
if (head == null)
return 0;
Stack<Integer> stack = new Stack<>();
while (head != null) {
stack.push(head.val);
head = head.next;
}
int mark = 1;
int ans = 0;
while (!stack.isEmpty()) {
ans += stack.pop() * mark;
mark <<= 1;
}
return ans;
}
}
class Solution {
public int getDecimalValue(ListNode head) {
if(head==null){
return 0;
}
StringBuffer sb = new StringBuffer();
while(head!=null){
sb.append(head.val);
head = head.next;
}
return Integer.parseInt(sb.toString(),2);
}
}
你知道的越多,你不知道的越多。
有道无术,术尚可求,有术无道,止于术。
如有其它问题,欢迎大家留言,我们一起讨论,一起学习,一起进步