[Java]LeetCode1115. 交替打印FooBar | Print FooBar Alternately

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

Suppose you are given the following code:

class FooBar {
public void foo() {
    for (int i = 0; i < n; i++) {
      print("foo");
  }
}

public void bar() {
    for (int i = 0; i < n; i++) {
      print("bar");
    }
}
}
The same instance of FooBar will be passed to two different threads. Thread A will call foo() while thread B will call bar(). Modify the given program to output "foobar" n times.

 

Example 1:

Input: n = 1
Output: "foobar"
Explanation: There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar(). "foobar" is being output 1 time.
Example 2:

Input: n = 2
Output: "foobarfoobar"
Explanation: "foobar" is being output 2 times.


我们提供一个类:

class FooBar {
public void foo() {
    for (int i = 0; i < n; i++) {
      print("foo");
  }
}

public void bar() {
    for (int i = 0; i < n; i++) {
      print("bar");
    }
}
}
两个不同的线程将会共用一个 FooBar 实例。其中一个线程将会调用 foo() 方法,另一个线程将会调用 bar() 方法。

请设计修改程序,以确保 "foobar" 被输出 n 次。

 

示例 1:

输入: n = 1
输出: "foobar"
解释: 这里有两个线程被异步启动。其中一个调用 foo() 方法, 另一个调用 bar() 方法,"foobar" 将被输出一次。
示例 2:

输入: n = 2
输出: "foobarfoobar"
解释: "foobar" 将被输出两次。


15ms

 1 import java.util.concurrent.locks.Condition;
 2 import java.util.concurrent.locks.Lock;
 3 import java.util.concurrent.locks.ReentrantLock;
 4 
 5 class FooBar {
 6     private int n;
 7     private boolean fooFlag;
 8     private boolean barFlag;
 9     private Lock lock;
10     private Condition fooCondition;
11     private Condition barCondition;
12 
13     public FooBar(int n) {
14         this.n = n;
15         this.fooFlag = false;
16         this.barFlag = true;
17         this.lock = new ReentrantLock();
18         this.fooCondition = lock.newCondition();
19         this.barCondition = lock.newCondition();
20     }
21 
22     public void foo(Runnable printFoo) throws InterruptedException {
23         for (int i = 0; i < n; i++) {
24             lock.lock();
25 
26             try {
27                 while (fooFlag) {
28                     fooCondition.await();
29                 }
30 
31                 /**
32                  * printFoo.run() outputs "foo". Do not change or remove this line.
33                  */
34                 printFoo.run();
35                 fooFlag = true;
36                 barFlag = false;
37                 barCondition.signal();
38             } finally {
39                 lock.unlock();
40             }
41         }
42     }
43 
44     public void bar(Runnable printBar) throws InterruptedException {
45         for (int i = 0; i < n; i++) {
46             lock.lock();
47 
48             try {
49                 while (barFlag) {
50                     barCondition.await();
51                 }
52 
53                 /**
54                  * printBar.run() outputs "bar". Do not change or remove this line.
55                  */
56                 printBar.run();
57                 barFlag = true;
58                 fooFlag = false;
59                 fooCondition.signal();
60             } finally {
61                 lock.unlock();
62             }
63         }
64     }
65 }

16ms

 1 import java.util.concurrent.Semaphore;
 2 
 3 class FooBar {
 4     private int n;
 5     private Semaphore semaphore = new Semaphore(1);
 6     private Semaphore semaphore2 = new Semaphore(0);
 7     public FooBar(int n) {
 8         this.n = n;
 9     }
10 
11     public void foo(Runnable printFoo) throws InterruptedException {
12         
13         for (int i = 0; i < n; i++) {
14             semaphore.acquire();
15             // printFoo.run() outputs "foo". Do not change or remove this line.
16             printFoo.run();
17             semaphore2.release();
18         }
19     }
20 
21     public void bar(Runnable printBar) throws InterruptedException {
22         
23         for (int i = 0; i < n; i++) {
24             semaphore2.acquire();
25             // printBar.run() outputs "bar". Do not change or remove this line.
26             printBar.run();
27             semaphore.release();
28         }
29     }
30 }

24ms

 1 class FooBar {
 2     private int n;
 3     private static final Object LOCK = new Object();
 4     public FooBar(int n) {
 5         this.n = n;
 6     }
 7 
 8     public void foo(Runnable printFoo) throws InterruptedException {
 9         for (int i = 0; i < n; i++) {
10             synchronized (LOCK) {
11                 LOCK.notify();
12                 printFoo.run();
13                 LOCK.wait();
14             }
15         }
16     }
17 
18     public void bar(Runnable printBar) throws InterruptedException {
19         for (int i = 0; i < n; i++) {
20             synchronized (LOCK) {
21                 LOCK.notify();
22                 printBar.run();
23                 if (i < n - 1) {
24                     LOCK.wait();
25                 }
26             }
27         }
28     }
29 }

 

转载于:https://www.cnblogs.com/strengthen/p/11289225.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用Java中的排序功能来实现。可以使用Arrays.sort()函数,将列表中的元素按照字母顺序排序,或者使用Collections.sort()函数,将列表中的元素按用户指定的排序规则排序。 ### 回答2: 为了实现LeetCode 2561题(Rearranging Fruits)的要求,需要使用Java编程语言。主要思路是遍历给定的水果数组,同时用一个哈希表来记录每个水果出现的次数。然后根据题目要求,重新排列水果使得相同类型的水果尽可能接近,并且按照出现次数的非递增顺序排序。 具体实现步骤如下: 1. 创建一个HashMap来存储每个水果的出现次数。遍历给定的水果数组,如果该水果已经存在于HashMap中,则将其出现次数加1;否则,将该水果添加到HashMap,并将其出现次数初始化为1。 2. 创建一个ArrayList来存储已经排列好的水果。通过HashMap的entrySet方法获取到每种水果和它的出现次数,然后将这些entry按照出现次数的非递增顺序进行排序。 3. 遍历排序好的entry集合,根据每个水果的出现次数,在ArrayList中连续添加相应数量的水果。 4. 返回排列好的水果数组。 以下是Java代码的示例实现: ```java import java.util.*; class Solution { public String[] rearrange(String[] fruits) { HashMap<String, Integer> fruitCountMap = new HashMap<>(); // 统计每个水果的出现次数 for (String fruit : fruits) { if (fruitCountMap.containsKey(fruit)) { fruitCountMap.put(fruit, fruitCountMap.get(fruit) + 1); } else { fruitCountMap.put(fruit, 1); } } ArrayList<Map.Entry<String, Integer>> sortedEntries = new ArrayList<>(fruitCountMap.entrySet()); // 根据出现次数进行非递增排序 Collections.sort(sortedEntries, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> entry1, Map.Entry<String, Integer> entry2) { return entry2.getValue().compareTo(entry1.getValue()); } }); ArrayList<String> rearrangedFruits = new ArrayList<>(); // 根据出现次数连续添加水果 for (Map.Entry<String, Integer> entry : sortedEntries) { String fruit = entry.getKey(); int count = entry.getValue(); for (int i = 0; i < count; i++) { rearrangedFruits.add(fruit); } } return rearrangedFruits.toArray(new String[0]); } } ``` 使用以上代码,可以对给定的水果数组进行重新排列,使得相同类型的水果尽可能接近,并且按照出现次数的非递增顺序进行排序。返回的结果就是排列好的水果数组。 ### 回答3: 题目要求将一个字符串中的水果按照特定规则重新排列。我们可以使用Java来实现这个问题。 首先,我们需要定义一个函数来解决这个问题。 ```java public static String rearrangeFruits(String fruits) { // 将字符串转换为字符数组方便处理 char[] fruitArray = fruits.toCharArray(); // 统计每种水果的数量 int[] fruitCount = new int[26]; for (char fruit : fruitArray) { fruitCount[fruit - 'a']++; } // 创建一个新的字符数组来存储重新排列后的结果 char[] rearrangedFruitArray = new char[fruitArray.length]; // 逐个将水果按照规则放入新数组中 int index = 0; for (int i = 0; i < 26; i++) { while (fruitCount[i] > 0) { rearrangedFruitArray[index++] = (char) ('a' + i); fruitCount[i]--; } } // 将字符数组转换为字符串并返回 return new String(rearrangedFruitArray); } ``` 上述代码中,我们首先将字符串转换为字符数组,并使用一个长度为26的数组来统计每一种水果的数量。然后,我们创建一个新的字符数组来存储重新排列后的结果。 接下来,我们利用双重循环将每一种水果按照规则放入新数组中。最后,我们将字符数组转换为字符串并返回。 例如,如果输入字符串为`"acbba"`,则经过重新排列后,输出结果为`"aabbc"`。 这样,我们就用Java实现了题目要求的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值